2

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?

Julia
  • 219
  • 2
  • 8
  • Either use a string format or use some form of `eval` (extremely dangerous - this is user input!). So - use a string format of a list (`example.py 1,2,3 3,4,5`). – Reut Sharabani Sep 12 '15 at 23:54
  • @ReutSharabani I cannot do that, the program will be tested as shown in my question. – Julia Sep 12 '15 at 23:56
  • You can use `ast.literal_eval`. `eval` is probably fine for a test program that only you will run. – Colonel Thirty Two Sep 12 '15 at 23:58
  • This means you'll have to parse the input. If it's just a stringified list you may be able to use the `json` module on each of the arguments. I'm not sure about the security `literal_eval` offers so I'm not going to offer it :-) – Reut Sharabani Sep 12 '15 at 23:58
  • You get args in `sys.argv`. You just have to parse them. Please don't ask people to do your homework. – spectras Sep 12 '15 at 23:58
  • 2
    There is an extended code example of using ast.literal_eval to pass lists, dicts and tuples to Python on the command line at http://stackoverflow.com/questions/7605631/passing-a-list-to-python-from-command-line, see answer by the-wolf. –  Sep 13 '15 at 02:13

3 Answers3

1
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.

hilberts_drinking_problem
  • 11,322
  • 3
  • 22
  • 51
1

[ 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]
Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670
0
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']
trishnag
  • 182
  • 1
  • 3
  • 13