argparse subparser --help output doesn't show the subparser's description

独自空忆成欢 提交于 2020-01-11 11:28:43

问题


If I create a subparser with a specific help string, this string is not displayed when the user runs myprog command --help:

parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(help="sub-command help")

parser_command = subparsers.add_parser("command", help="Issue a command")
parser.parse_args()

The top-level help shows this command subcommand with the description "Issue a command" alongside:

$ python prog.py --help
usage: prog.py [-h] {command} ...

positional arguments:
  {command}   sub-command help
    command   Issue a command

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

However the subcommand's help doesn't show this description:

$ python prog.py command --help
usage: prog.py command [-h]

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

What I would expect is for the subcommand's help to print out what the subcommand is actually for. I.e. I expected to see the text "Issue a command" somewhere in the output to python prog.py command --help.

Is there a way to include this text in the subcommand's help output? Is there another subparser attribute that can be used to provide a description of the subcommand?


回答1:


The add_parser method accepts (most) of the parameters that a ArgumentParser constructor does.

https://docs.python.org/3/library/argparse.html#sub-commands

It's easy to overlook this sentence in the add_subparsers paragraph:

This object has a single method, add_parser(), which takes a command name and any ArgumentParser constructor arguments, and returns an ArgumentParser object that can be modified as usual.

In [93]: parser=argparse.ArgumentParser()

In [94]: sp = parser.add_subparsers(dest='cmd',description='subparses description')

In [95]: p1 = sp.add_parser('foo',help='foo help', description='subparser description')
In [96]: p1.add_argument('--bar');

help for the main parser:

In [97]: parser.parse_args('-h'.split())
usage: ipython3 [-h] {foo} ...

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

subcommands:
  subparses description

  {foo}
    foo       foo help
...

help for the subparser:

In [98]: parser.parse_args('foo -h'.split())
usage: ipython3 foo [-h] [--bar BAR]

subparser description

optional arguments:
  -h, --help  show this help message and exit
  --bar BAR
...


来源:https://stackoverflow.com/questions/52194874/argparse-subparser-help-output-doesnt-show-the-subparsers-description

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!