Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Argparse: Default values not shown for subparsers

I have the problem that I am not seeing any default values for arguments when specifying them via add_argument for subparsers using the argparse Python package.

Some research said that you need non-empty help-parameters set for each add_argument step and you need ArgumentDefaultsHelpFormatter as formatter_class as described here:

Argparse: Way to include default values in '--help'?

That's not working for me, however. I suspect that somehow the subparser defaults are suppressed.

Here's an example:

from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter

parser = ArgumentParser(description="Sample script", formatter_class=ArgumentDefaultsHelpFormatter, version="sample version")

# Initialize Subparsers

subparsers = parser.add_subparsers(help="", dest="command")

# foo command

fooparser = subparsers.add_parser('foo', help='Do foo')
fooparser.add_argument('files', action='store', help='Foo file(s)' , nargs="+")
fooparser.add_argument("-5", "--Do5", type=int, required=False, dest="do5", help="Do 5 subprocedure.")
fooparser.add_argument("-n", "--topn", type=int, required=False, dest="topn", default=1, help="Show topn")

# bar command

barparser = subparsers.add_parser('bar', help='Do bar')
barparser.add_argument('files', action='store', help='Bar file(s)' , nargs="+")
barparser.add_argument("-mq", "--min-mq", type=int, required=False, default=2, dest="mq", help="Minimum MQ")
barparser.add_argument("-mi", "--min-identity", type=float, required=False, default=0.95, dest="identity", help="Minimum identity")

args = parser.parse_args()
like image 568
fh_fingolfin Avatar asked Oct 12 '16 11:10

fh_fingolfin


1 Answers

Specify formatter_class when adding sub-parsers.

subparsers = parser.add_subparsers(help="", dest="command")

fooparser = subparsers.add_parser('foo', help='Do foo',
                                  formatter_class=ArgumentDefaultsHelpFormatter)
...

barparser = subparsers.add_parser('bar', help='Do bar',
                                  formatter_class=ArgumentDefaultsHelpFormatter)
...

Output of python argparse_test.py --help foo:

usage: argparse_test.py foo [-h] [-5 DO5] [-n TOPN] files [files ...]

positional arguments:
  files                 Foo file(s)

optional arguments:
  -h, --help            show this help message and exit
  -5 DO5, --Do5 DO5     Do 5 subprocedure. (default: None)
  -n TOPN, --topn TOPN  Show topn (default: 1)
like image 118
falsetru Avatar answered Sep 22 '22 12:09

falsetru