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?
To add an optional argument, simply omit the required parameter in add_argument() . args = parser. parse_args()if args.
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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With