gpt4 book ai didi

python - 使用 RubyPython 执行任意 python 代码块

转载 作者:数据小太阳 更新时间:2023-10-29 09:03:13 28 4
gpt4 key购买 nike

我正在尝试使用 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

我收到语法错误,意外的':'

那么我该如何使用这个模块来执行这个 python 代码块呢?更重要的是,我如何将值从 Ruby 传递到正在执行的 Python 代码中?

最佳答案

因为没有人回答,我设法找到了东西(虽然那是一个非常丑陋的东西)。

我完全不确定这是否是使用 RubyPython 的预期方法,但我能够通过执行以下一组任务来实现功能:

 > 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

同样,这是否是“正确”的做法还有待商榷 - 但它确实有效。

关于python - 使用 RubyPython 执行任意 python 代码块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30289911/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com