0

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?

karthikr
  • 97,368
  • 26
  • 197
  • 188
Avaclon
  • 163
  • 6
  • 1
    *optional*? and how it's supposed to tell whether the next word is the optional parameter or the next argument? your grammar is ambiguous. – Karoly Horvath Jun 30 '14 at 15:31

1 Answers1

1

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

Chris Clarke
  • 2,103
  • 2
  • 14
  • 19