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?

JohnJ
  • 6,736
  • 13
  • 49
  • 82
  • 1
    It's certainly possible, but you'll have to do careful quoting to get expressions with [ ] through your average shell. – Roland Weber Jun 04 '19 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. – Blorgbeard Jun 04 '19 at 20:36
  • 1
    `argparse` might be of help, check out similar question [here](https://stackoverflow.com/questions/15753701/argparse-option-for-passing-a-list-as-option) – jean Jun 04 '19 at 20:50
  • @jean Yes! Especially [this answer](https://stackoverflow.com/a/57113295/4518341) – wjandrea Sep 01 '19 at 21:10

2 Answers2

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]
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Ankit
  • 604
  • 6
  • 13
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)
wjandrea
  • 28,235
  • 9
  • 60
  • 81