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?

6
  • 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). Commented Sep 12, 2015 at 23:54
  • @ReutSharabani I cannot do that, the program will be tested as shown in my question. Commented Sep 12, 2015 at 23:56
  • You can use ast.literal_eval. eval is probably fine for a test program that only you will run. Commented Sep 12, 2015 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 :-) Commented Sep 12, 2015 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 stackoverflow.com/questions/7605631/…, see answer by the-wolf. Commented Sep 13, 2015 at 2:13

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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]

Comments

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']

1 Comment

I don't think that is what the OP is trying to do, '1,2,3' is still a string (and not a list)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.