python argparse choices with a default choice

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.


Documention:

nargs with '?'

One argument will be consumed from the command line if possible, and produced as a single item. If no command-line argument is present, the value from default will be produced. Note that for optional arguments, there is an additional case – the option string is present but not followed by a command-line argument. In this case the value from const will be produced.

const

When add_argument() is called with option strings (like -f or --foo) and nargs="?". This creates an optional argument that can be followed by zero or one command-line arguments. When parsing the command line, if the option string is encountered with no command-line argument following it, the value of const will be assumed instead. See the nargs description for examples.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)