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?
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?
 
    
    import ast
import sys
for arg in sys.argv:
    try:
        print sum(ast.literal_eval(arg))
    except:
        pass
In command line:
   >>= python passListAsCommand.py "[1,2,3]"
    6
Be careful not to pass anything malicious to literal_eval.
 
    
    [ 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']
