Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python argparse choices with a default choice

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?

like image 267
MVanOrder Avatar asked Oct 29 '16 22:10

MVanOrder


People also ask

How do you add an optional argument in Argparse?

To add an optional argument, simply omit the required parameter in add_argument() . args = parser. parse_args()if args.

What is Store_true in Python?

The store_true option automatically creates a default value of False. Likewise, store_false will default to True when the command-line argument is not present.

What does parse_args return?

Adding arguments Later, calling parse_args() will return an object with two attributes, integers and accumulate . The integers attribute will be a list of one or more ints, and the accumulate attribute will be either the sum() function, if --sum was specified at the command line, or the max() function if it was not.

What is Argparse ArgumentParser ()?

The argparse module provides a convenient interface to handle command-line arguments. It displays the generic usage of the program, help, and errors. The parse_args() function of the ArgumentParser class parses arguments and adds value as an attribute dest of the object.


1 Answers

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.

like image 188
Francisco Avatar answered Oct 05 '22 23:10

Francisco