ruby调用python脚本_Ruby:获取python脚本的返回值(Ruby: get return value of python script)

本文探讨了如何在Python脚本中打印值而不是返回,并在Ruby中使用backticks捕获输出。通过JSON作为交换格式,将Python列表转换为Ruby数组,解决了不同语言间的数据转换问题。同时提到了安全解析字符串到Ruby数组的方法,以及在没有Python的ast.literal_eval等安全函数的情况下,使用第三方库如parsr进行解析。
摘要由CSDN通过智能技术生成

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`)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值