Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`argparse` multiple choice argument?

I am using argparse to parse the Python command line which is supposed to look like this:

python script_name.py --sdks=first, second

My script looks like this:

sdk_choises = ['aio','sw']
parser = argparse.ArgumentParser(description='Blah blah')
parser.add_argument('--sdks', action='append', nargs='+', required=True, help='specifies target SDK(s)')
args = parser.parse_args()
if 'aio' in args.sdks:
   # do something with aio
if 'sw' in args.sdks:
   # do something with sw

When I execute: python script_name.py --sdks=aio, sw I get error:

"usage: script.py [-h] --sdks SDKS [SDKS ...]  
build.py: error: unrecognized arguments: sw"

I'd like to be able to choose one or all choices:

python script_name.py --sdks=first
python script_name.py --sdks=second
python script_name.py --sdks=first, second

Where did I go wrong?

like image 732
Danijel Avatar asked Sep 15 '15 10:09

Danijel


2 Answers

The following works nice:

import argparse
parser = argparse.ArgumentParser(description='Blah blah')
parser.add_argument('--sdks', nargs='+', required=True, help='specifies target SDK(s)')
args = parser.parse_args()
print(args.sdks)

You don't need the = when passing options, just use:

$ python test.py --sdks ai pw
['ai', 'pw']
like image 130
serge-sans-paille Avatar answered Oct 07 '22 22:10

serge-sans-paille


If you prefer your original form of the comma-separated list, plus check if the argument is valid, then I recommend:

parser.add_argument('--sdks', nargs=1, type=lambda s: [sdk_choises[sdk_choises.index(f)] for f in s.split(',')], ...

Even cleaner way is to define it in a separate function similar to lambda above:

parser.add_argument('--sdks', nargs=1, type=my_parse_function, ...

argparse docs has examples for the parsing function with proper error reporting. With nargs=1 you'd need to remove one extra list layer.

like image 43
Дмитрий Чернявский Avatar answered Oct 07 '22 22:10

Дмитрий Чернявский