2

我正在尝试使用 RubyPython 模块(https://github.com/halostatue/rubypython)从 Ruby 脚本中执行 Python 代码。我已经正确设置了模块,但是我很困惑如何使用它。

如果我有一段 Python 代码作为文本,请说:

def multiply(x, y):
    return x * y * y

z = multiply(x, y)

我如何能够将它传递给 Python 以在 Ruby 中动态定义的“x”和“y”执行,然后能够检索“z”的值?

根据评论请求进行编辑 到目前为止,这对我来说很有效并且很有意义:

RubyPython.start(python_exe: "/usr/bin/python2.6")
cPickle = RubyPython.import("cPickle")
p cPickle.dumps("Testing RubyPython.").rubify
RubyPython.stop # stop the Python interpreter    

这给了我一个输出"S'Testing RubyPython.'\n."

我可以像这样运行非常简单的命令:

RubyPython.start(python_exe: "/usr/bin/python2.6")
x = 3
y = x * x * x
print "y = %d" % y
RubyPython.stop # stop the Python interpreter

"y = 27"正如预期的那样,这给了我一个输出。

但是一旦我尝试在 python 中定义一个方法,我就会得到一系列错误:

RubyPython.start(python_exe: "/usr/bin/python2.6")
def my_multiply(x, y):
  return x * y * y
z = my_multiply(2, 3)
print "z = %d" % z
RubyPython.stop # stop the Python interpreter    

我明白了syntax error, unexpected ':'

So how would I execute this block of python code using this module? And more importantly, how would I pass values in from Ruby into the Python code that is executing?

4

1 回答 1

2

Since no answer has been made, and I managed to find something (although a very ugly something at that).

I'm not sure at all if this is the intended method to use RubyPython but I was able to get things to function by doing the following set of tasks:

 > RubyPython.start
 > RubyPython::Python.PyRun_SimpleString <<-PYTHON
*> def test():
*>     print("Hello, World")
*> PYTHON
 > main = RubyPython.import("__main__")
 > main.test()
 >>> Hello, World!
 > RubyPython::Python.PyRun_SimpleString <<-PYTHON
*> def my_mult(x, y):
*>     return x * y
*> PYTHON
 > main.my_mult(10, 20).rubify
 >>> 200

Again, whether this is the "correct" way to do it, or not is up for debate - but it worked.

于 2015-05-18T21:12:56.833 回答