简体   繁体   English

将数组作为命令行参数传递给python脚本

[英]passing array as command line argument to python script

I am calling a python script from a ruby program as: 我从Ruby程序中调用python脚本为:

sku = ["VLJAI20225", "VJLS1234"]
qty = ["3", "7"]
system "python2 /home/nish/stuff/repos/Untitled/voylla_staging_changes/app/models/ReviseItem.py #{sku} #{qtys}"

But I'd like to access the array elements in the python script. 但是我想访问python脚本中的数组元素。

print sys.argv[1]      
#gives [VLJAI20225,  expected ["VLJAI20225", "VJLS1234"]
print sys.argv[2]
#gives VJLS1234]     expected ["3", "7"]

I feel that the space between the array elements is treating the array elements as separate arguments. 我觉得数组元素之间的空间将数组元素视为单独的参数。 I may be wrong. 我可能是错的。

How can I pass the array correctly? 如何正确传递数组?

Not a python specialist, but a quick fix would be to use json: 不是python专家,但快速解决方案是使用json:

system "python2 /home/nish/stuff/repos/Untitled/voylla_staging_changes/app/models/ReviseItem.py #{sku.to_json} #{qtys.to_json}"

Then parse in your python script. 然后解析您的python脚本。

You need to find a suitable protocol to encode your data (your array, list, whatever) over the interface you've chosen (this much is true pretty general). 您需要找到一种合适的协议,以通过您选择的接口对数据(数组,列表等)进行编码(这是相当普遍的事实)。

In your case, you've chosen as interface the Unix process call mechanism which allows only passing of a list of strings during calling. 在您的情况下,您选择了Unix进程调用机制作为接口,该机制仅允许在调用过程中传递字符串列表。 This list also is rather limited (you cannot pass, say, a gigabyte that way), so you might want to consider passing data via a pipe between the two processes. 此列表也相当有限(您不能以这种方式传递1 GB的数据),因此您可能要考虑通过两个进程之间的管道传递数据。

Anyway, all you can do is pass bytes, so I propose to encode your data accordingly, eg as a JSON string. 无论如何,您所能做的就是传递字节,因此我建议对数据进行相应的编码,例如作为JSON字符串。 That means encode your Ruby array in JSON, transfer that JSON string, then decode on the Python side the received JSON string to get a proper Python list again. 这意味着将您的Ruby数组编码为JSON,传输该JSON字符串,然后在Python端解码接收到的JSON字符串,以再次获得正确的Python列表。

This only sketches the approach and reasoning behind it. 这仅勾勒出其背后的方法和推理。

Since I'm not fluent in Ruby, I will leave that part to you (see probably @apneadiving's answer on that), but on the Python side you can use 由于我不太会使用Ruby,因此我将把这一部分留给您(可能会看到@apneadiving的答案),但是在Python方面,您可以使用

import json

myList = json.loads(s)

to convert a JSON string s to a Python list myList . 一个JSON字符串转换s到Python的列表myList

"python2 /home/nish/stuff/repos/Untitled/voylla_staging_changes/app/models/ReviseItem.py \'#{sku}\' \'#{qtys}\'"

也许是这样的吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM