Optional parameters to arguments along with sub commands using argparse

755 Views Asked by At

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?

1

There are 1 best solutions below

0
On

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 subparser

main_parser = argparse.ArgumentParser()
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('--test', action='store', nargs='?', dest='test_server', help='Use test server')
build_parser.add_argument('--name', action='store', nargs=1, dest='build_name')

Then your syntax would be:

python test.py build --test "<random http>" --name foobar

try looking at argparse#nargs