I'm having trouble trying to allow for optional test parameters to be inserted into CLI I'm created. Here's what I've able to do:
python test.py --test build --name foobar
Where build is a subcommand, and --test allows for the system to point to the default test server. However, I would like to allow users to specified an additional, optional, server property after the --test so users can point the test server whereever they want. Example:
python test.py --test "<random http>" build --name foobar
My code currently looks like this:
main_parser = argparse.ArgumentParser()
main_parser.add_argument('--test', action='store', nargs=1, dest='test_server', help='Use test server')
subparsers = main_parser.add_subparsers(help='SubCommands', dest='command')
build_parser = subparsers.add_parser('build', help = 'lists the build command(s) for the specified view/warehouse')
build_parser.add_argument('--name', action='store', nargs=1, dest='build_name')
However, no matter what I change the nargs to, it starts disallow the original, which is just --test. Is there a way I can have both?
You can have an optional nargs, using
nargs='?'
, but as Karoly Horvath states, your grammar is ambiguous. You be much better off adding --test to your build subparserThen your syntax would be:
try looking at
argparse#nargs