nish
nish

Reputation: 7280

passing array as command line argument to python script

I am calling a python script from a ruby program as:

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.

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?

Upvotes: 1

Views: 2937

Answers (3)

Alfe
Alfe

Reputation: 59426

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. 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.

Anyway, all you can do is pass bytes, so I propose to encode your data accordingly, e. g. as a JSON string. 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.

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

import json

myList = json.loads(s)

to convert a JSON string s to a Python list myList.

Upvotes: 3

GMPrazzoli
GMPrazzoli

Reputation: 239

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

Maybe something like this?

Upvotes: 1

apneadiving
apneadiving

Reputation: 115511

Not a python specialist, but a quick fix would be to use 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.

Upvotes: 3

Related Questions