如何从Ruby调用Python代码?

时间:2009-05-07 21:59:02

标签: python ruby

是否存在易于使用的Ruby to Python桥接?或者我最好使用system()?

5 个答案:

答案 0 :(得分:6)

您可以尝试Masaki Fukushima's library将python嵌入ruby中,尽管它似乎没有得到维护。 YMMV

  

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

来自巧妙的为什么幸运僵硬的有趣名字Unholy也可能有用:

  

将Ruby编译为Python字节码   而且,另外,翻译一下   字节码回到Python源代码   使用Decompyle(包括。)

     

需要Ruby 1.9和Python 2.5。

答案 1 :(得分:6)

gem install ruby​​python

rubypython home page

答案 2 :(得分:2)

我认为没有办法从Ruby调用Python而不需要通过system()或其他东西来分配进程。语言运行时间完全不同,无论如何它们都需要处于不同的进程中。

答案 3 :(得分:0)

如果您想使用Python代码,就像您的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

输出: 2009东海生日贺 YM EMAN SI ymmij

答案 4 :(得分:-1)

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

为了调用你可以使用RPC或网络套接字的python代码,可以使用最简单的东西。