0

I think the question is self explanatory. I would like to use a list of list as a command line argument like so:

python3 awesome_code.py --list=[[var1,var2],[var3,v4]..]

Is this possible at all?

4
  • 1
    It's certainly possible, but you'll have to do careful quoting to get expressions with [ ] through your average shell. Commented Jun 4, 2019 at 20:28
  • 1
    It's not exactly possible. Command-line arguments are strings only. You can pass a string that looks like a list, but you'll have to parse it to get a python list out of it. Commented Jun 4, 2019 at 20:36
  • 1
    argparse might be of help, check out similar question here Commented Jun 4, 2019 at 20:50
  • @jean Yes! Especially this answer Commented Sep 1, 2019 at 21:10

2 Answers 2

1

You can use json.loads for this.

import json
import sys
l = json.loads(sys.argv[1])
for x in l:
    print(x)
python3 test.py [[1,2,3],[4,5,6]] 

Output:

[1, 2, 3]
[4, 5, 6]
Sign up to request clarification or add additional context in comments.

Comments

0

You could use argparse to define a more typical shell command line like this:

python3 awesome_code.py --list v1 v2 --list v3 v4

Where the result would be

[['v1', 'v2'], ['v3', 'v4']]

Here is the example code:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument(
    '--list',
    action='append',
    nargs='*',
    )
args = parser.parse_args('--list v1 v2 --list v3 v4'.split())
print(args.list)

Comments

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.