Search code examples
pythonargparsesubparsers

How to perform an argparse subparse for [-A[-b value]] in Python


I want to recreate [-A [-b value]] where in command would look like this:

test.py -A -b 123

Seems really simple but I can't get it right. My latest attempt has been:

byte = subparser.add_parser("-A")
byte.add_argument("-b", type=int)

Solution

  • While the add_parser command accepts '-A', the parser cannot use it. Look at the help:

    usage: ipython3 [-h] {-A} ...
    
    positional arguments:
      {-A}
    
    optional arguments:
      -h, --help  show this help message and exit
    

    A subparser is really a special kind of positional argument. To the main parser, you have effectively defined

    add_argument('cmd', choices=['-A'])
    

    But to the parsing code, '-A' looks like an optional's flag, as though you had defined

    add_argument('-A')
    

    The error:

    error: argument cmd: invalid choice: '123' (choose from '-A')
    

    means that it has skipped over the -A and -b (which aren't defined for the main parser), and tried to parse '123' as the first positional. But it isn't in the list of valid choices.

    So to use subparsers, you need specify 'A' as the subparser, not '-A'.