如何从Ruby调用Python代码?

5

是否存在易于使用的Ruby到Python桥接工具?或者我最好使用system()函数?


我之前在这里问过一个类似的问题,也许那些答案会有所帮助:https://dev59.com/AnE95IYBdhLWcg3wMrEB。 - Yktula
5个回答

6

6
你可以尝试使用Masaki Fukushima的库将Python嵌入Ruby中,尽管它似乎没有得到维护。YMMV
使用此库,Ruby脚本可以直接调用任意Python模块。可以使用扩展模块和用Python编写的模块。
巧妙地命名为Unholy的来自天才Why the Lucky Stiff的工具也可能有用:
将Ruby编译为Python字节码。另外,使用Decompyle(已包含)将该字节码转换回Python源代码。
需要Ruby 1.9和Python 2.5。

不错。之前没听说过unholy。 - Andrew Grimm

2
我认为没有办法在不通过fork进程(例如通过system())的情况下从Ruby调用Python。这两种语言的运行时完全不同,它们必须在单独的进程中运行。

通过subprocess模块调用进程。system()功能不足,让我们杀死这只野兽。 - nosklo

0
如果你想把 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

那么你的Python脚本应该长这样

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

输出: olleh ym eman si ymmij


2
作者希望从 Ruby 中调用 Python 代码,而不是从 Python 中调用 Ruby 代码。 - Andy Obusek

-1

为了让Python代码运行,解释器需要作为进程启动。因此,system()是您最好的选择。

要调用Python代码,可以使用RPC或网络套接字,请尽可能简单地实现。


太好了,这正是我打算做的。我认为没有必要比单独使用system()更花哨。 - Eric
2
我认为这并不完全正确:请参阅http://docs.python.org/extending/embedding.html,了解将Python解释器嵌入到另一个应用程序中的文档。这也可以是Ruby解释器,如果你想要这样做的话。 - Mike Woodhouse

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接