yogesh yogesh - 6 months ago 46
Python Question

How to pass an entire list as command line argument in Python?

I was trying to pass two lists containing integers as arguments to a python code. But

sys.argv[i]
gets the parameters as a list of string.

Input would look like,

$ python filename.py [2,3,4,5] [1,2,3,4]


I found the following hack to convert the list.

strA = sys.argv[1].replace('[', ' ').replace(']', ' ').replace(',', ' ').split()
strB = sys.argv[2].replace('[', ' ').replace(']', ' ').replace(',', ' ').split()
A = [float(i) for i in strA]
B = [float (i) for i in strB]


Is there a better way to do this?

Answer Source

Command line arguments are always passed as strings. You will need to parse them into your required data type yourself.

>>> input = "[2,3,4,5]"
>>> map(float, input.strip('[]').split(','))
[2.0, 3.0, 4.0, 5.0]
>>> A = map(float, input.strip('[]').split(','))
>>> print(A, type(A))
([2.0, 3.0, 4.0, 5.0], <type 'list'>)

Their are libraries like argparse and click that let you define your own argument type conversion but argparse treats "[2,3,4]" the same as [ 2 , 3 , 4 ] so I doubt it will be useful.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download