Search code examples
pythonargparse

`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?


Solution

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