First, have your Python script print the value rather than returning it, or add print main() at the bottom so the return value of main() gets printed.
Second, on the Ruby side, execute it with backticks rather than the system() function, like this:
output = `python script.py`
This captures the output of the Python script as a string. If you want it as a Ruby array, you'll need to parse it. Ruby's array literal syntax is similar to Python's list literal syntax, so this is not as tough as it might seem. If you can find something that parses strings into Ruby arrays (besides eval() because it's dangerous) you should be covered. Problems will arise when you have things besides simple types, None, or potentially strings with escapes in them.
I am more a Python guy than a Ruby guy, but Ruby doesn't seem to have anything like Python's ast.literal_eval (a safe eval() that only accepts literals) in its standard library. However, I did find parsr which appears to be exactly that.
If the Python list literals you're getting aren't valid Ruby, you can use JSON as the interchange format:
# Python side
import json, sys
json.dump(main(), sys.stdout)
# Ruby side
require 'json'
output = JSON.parse(`python script.py`)
本文探讨了如何在Python脚本中打印值而不是返回,并在Ruby中使用backticks捕获输出。通过JSON作为交换格式,将Python列表转换为Ruby数组,解决了不同语言间的数据转换问题。同时提到了安全解析字符串到Ruby数组的方法,以及在没有Python的ast.literal_eval等安全函数的情况下,使用第三方库如parsr进行解析。
535

被折叠的 条评论
为什么被折叠?



