0

I have a perl script which calls a python function with an array as an argument. The python function needs to loop through the array elements. I tried below, but the python function reads the array as string.

my @stmts = ("cd /tmp", "touch test.txt")
python.exe test.py @stmts

Python

def test(stmts)
    print("Statements:" stmts)

I want to read stmts as a list in python. Any help on this is greatly appreciated. Thank you.

1

2 Answers 2

4

Arguments can only be strings. You can't pass an array. But since you have an array of strings, you can pass the strings as individual parameters.

system("script.py", @stmts);

They will be present as a list in sys.argv[1:].

stmts = sys.argv[1:]

For more complex structures, you will need to serialize and deserialize the data somehow. JSON is common choice, but many other options exist.

Sign up to request clarification or add additional context in comments.

2 Comments

AFAIK, depending on the OS/Perl version combination a shell may get involved even with the list form of system which means some kind of escaping or encoding of the arguments being passed becomes necessary. If this is greenfield, one might just want to go the JSON route from the get-go so as not to have to retrofit later.
@Sinan Ünür, yeah, on Windows, when the program (script.py) can't be found. system { "script.py" } "script.py", @stmts; guarantees no shell even in that situation.
-1

You can't pass an array to python from outside. It will be read as a string. You can convert the string to an array in your python code.

a = '["x","y","z"]'
print(a.replace("[",'').replace("]",'').replace('"','').split(','))
['x', 'y', 'z']

If you have parenthesis and quotes as part of the string then you will have to replace it. If you have just a string like 'x,y,z' the you can just do spilt(',') to get an array.

4 Comments

sure, will try to split in python. Thank you
You really should use YAML or jason to pass the data between languages. Saves a lot of trouble.
@G4143, Jason is overworked, and it takes time for him to type in the data. But JSON is pretty good ;)
@ikegami, Jason lives and is marshalling data!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.