如何从Ruby调用Python代码?

如何从Ruby调用Python代码?,python,ruby,Python,Ruby,是否存在易于使用的Ruby到Python桥接器?还是使用system()更好 我不认为有任何方法可以从Ruby调用Python,而不通过system()或其他方式派生进程。语言运行时是完全不同的,它们无论如何都需要在不同的进程中。您可以尝试在ruby中嵌入python,尽管它似乎没有得到维护。YMMV 有了这个库,Ruby脚本可以直接调用任意Python模块。可以使用扩展模块和用Python编写的模块 这个有趣的名字来源于《为什么幸运的僵硬可能也有用》一书: 将Ruby编译为Python字节码。

是否存在易于使用的Ruby到Python桥接器?还是使用system()更好

我不认为有任何方法可以从Ruby调用Python,而不通过system()或其他方式派生进程。语言运行时是完全不同的,它们无论如何都需要在不同的进程中。

您可以尝试在ruby中嵌入python,尽管它似乎没有得到维护。YMMV

有了这个库,Ruby脚本可以直接调用任意Python模块。可以使用扩展模块和用Python编写的模块

这个有趣的名字来源于《为什么幸运的僵硬可能也有用》一书:

将Ruby编译为Python字节码。
此外,请将其翻译为
字节码返回Python源代码 使用反样式(包括。)

需要Ruby 1.9和Python 2.5


为了让python代码运行,解释器需要作为一个进程启动。所以system()是最好的选择

对于调用python代码,您可以使用RPC或网络套接字,这是最简单的操作。

gem install rubypython


如果希望像使用函数一样使用Python代码,请尝试IO.popen

如果您想使用python脚本“reverse.py”反转数组中的每个字符串,您的ruby代码如下所示

strings = ["hello", "my", "name", "is", "jimmy"]
#IO.popen: 1st arg is exactly what you would type into the command line to execute your python script.
#(You can do this for non-python scripts as well.)
pythonPortal = IO.popen("python reverse.py", "w+")
pythonPortal.puts strings #anything you puts will be available to your python script from stdin
pythonPortal.close_write

reversed = []
temp = pythonPortal.gets #everything your python script writes to stdout (usually using 'print') will be available using gets
while temp!= nil
    reversed<<temp
    temp = pythonPortal.gets
end 

puts reversed
输出: 奥利 ym 伊曼 硅
ymmij

不错。我以前没听说过邪恶。太好了,这就是我打算做的。没有任何理由比单独使用system()更令人着迷。我认为这一点都不正确:有关将Python解释器嵌入另一个应用程序的文档,请参阅。对于有悖常理的人来说,可能是Ruby解释器。通过子流程模块调用流程。system()缺少很多,让我们杀了野兽吧;也许答案会有所帮助:。作者希望从ruby调用python代码,而不是从python调用ruby代码。
import sys

def reverse(str):
    return str[::-1]

temp = sys.stdin.readlines() #Everything your ruby programs "puts" is available to python through stdin
for item in temp:
    print reverse(item[:-1]) #Everything your python script "prints" to stdout is available to the ruby script through .gets
    #[:-1] to not include the newline at the end, puts "hello" passes "hello\n" to the python script