I would like to pass a list as a parameter using the command line, for example:
$python example.py [1,2,3] [4,5,6]
I want the first list [1,2,3] to be first_list and [4,5,6] to be second_list. How can I do this?
[ might be a shell meta-character. You could drop [] as @Reut Sharabani suggested:
$ python example.py 1,2,3 4,5,6
It is easy to parse such format:
#!/usr/bin/env python3
import sys
def arg2int_list(arg):
"""Convert command-line argument into a list of integers.
>>> arg2int_list("1,2,3")
[1, 2, 3]
"""
return list(map(int, arg.split(',')))
print(*map(arg2int_list, sys.argv[1:]))
# -> [1, 2, 3] [4, 5, 6]
import sys
def command_list():
l = []
if len(sys.argv) > 1:
for i in sys.argv[1:]:
l.append(i)
return l
print(command_list())
In the command line
$ python3 test105.py 1,2,3 4,5,6
['1,2,3', '4,5,6']
'1,2,3' is still a string (and not a list)
eval(extremely dangerous - this is user input!). So - use a string format of a list (example.py 1,2,3 3,4,5).ast.literal_eval.evalis probably fine for a test program that only you will run.jsonmodule on each of the arguments. I'm not sure about the securityliteral_evaloffers so I'm not going to offer it :-)