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.
CodePudding user response:
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.
CodePudding user response:
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.