2
votes

I wrote the following command-line parses by using argparse that make use of sub-commands.

import argparse

if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        formatter_class=argparse.ArgumentDefaultsHelpFormatter
    )

    sub_parser = parser.add_subparsers(title='sub commands',
                                       help='sub commands help')

    foo = sub_parser.add_parser('foo')
    foo.add_argument(
        '--a',
        action='store',
        default='1234',
        help='A'
    )

    parser.parse_args(['foo', '--help'])

When I print the usage help for sub-command foo, I would expect that the default value of the argument --a is shown. But that doesn't happen.

Here the current output:

usage: test_args.py foo [-h] [--a A]

optional arguments:
  -h, --help  show this help message and exit
  --a A       A

Process finished with exit code 0

By calling sub-commands foo without argument a, the default value is used. So, why isn't also the default value shown inside the usage output? Is that a bug?

Or do you know how to achieve that?

2
I don't know how to achieve this with argparse, but I know that would be easy to do with the docopt library, if that could help - olinox14
The subparsers need the formatter_class parameter as well. They don't inherit parameters from the main. - hpaulj
Keep in mind that the ArgumentDefaultsHelpFormatter doesn't do anything profound. It just changes help='A' to help=A (%{default}s)'. You can do that yourself when writing the help parameter. - hpaulj

2 Answers

0
votes

As suggested by @hpauly, I found a workaround by using (default: %(default)s).

foo = sub_parser.add_parser('foo')
foo.add_argument(
    '--a',
    action='store',
    default='1234',
    help='A. (default: %(default)s)'
)
0
votes

add_parser takes the same arguments as ArgumentParser, so you can just do formatter_class=argparse.ArgumentDefaultsHelpFormatter to set the default argument formatter for the subparser.