python argparse choices with a default choice

MVanOrder picture MVanOrder · Oct 30, 2016 · Viewed 49.1k times · Source

I'm trying to use argparse in a Python 3 application where there's an explicit list of choices, but a default if none are specified.

The code I have is:

parser.add_argument('--list', default='all', choices=['servers', 'storage', 'all'], help='list servers, storage, or both (default: %(default)s)') 
args = parser.parse_args()
print(vars(args))

However, when I run this I get the following with an option:

$ python3 ./myapp.py --list all
{'list': 'all'}

Or without an option:

$ python3 ./myapp.py --list
usage: myapp.py [-h] [--list {servers,storage,all}]
myapp.py: error: argument --list: expected one argument

Am I missing something here? Or can I not have a default with choices specified?

Answer

Francisco Couzo picture Francisco Couzo · Oct 30, 2016

Pass the nargs and const arguments to add_argument:

parser.add_argument('--list',
                    default='all',
                    const='all',
                    nargs='?',
                    choices=['servers', 'storage', 'all'],
                    help='list servers, storage, or both (default: %(default)s)')

If you want to know if --list was passed without an argument, remove the const argument, and check if args.list is None.