How to show help for all subparsers in argparse?

*爱你&永不变心* 提交于 2019-11-29 15:03:35

The problem is that in the lines:

subparsers=parser.add_subparsers(dest='action')
subparsers.add_parser('Restart',parents=[general_group,second_group])
subparsers.add_parser('Start',parents=[general_group])

You are adding general_group as parent to the subparsers, so the main parser does not know about them, which results in ./script.py -h to not show --threads. If you plan to put it as parent of all the subparsers then you should put it as top parser parent:

parser = argparse.ArgumentParser(parents=[general_group])
subparsers=parser.add_subparsers(dest='action')
subparsers.add_parser('Restart',parents=[second_group])
subparsers.add_parser('Start')

Which results in:

$ python script.py -h
usage: script.py [-h] [--threads] {Restart,Start} ...

positional arguments:
  {Restart,Start}

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

Note however that in this case the option is part only of the parent parser and not the subparsers, which means that the following:

$python script.py --threads Start

is correct, while:

$ python script.py Start --threads
usage: script.py [-h] [--threads] {Restart,Start} ...
script.py: error: unrecognized arguments: --threads

Because --threads is not "inherited" by the subparser. If you want to have --threads also in the subparser you must specify it in its parents argument:

parser = argparse.ArgumentParser(parents=[general_group])
subparsers=parser.add_subparsers(dest='action')
subparsers.add_parser('Restart',parents=[general_group, second_group])
subparsers.add_parser('Start', parents=[general_group])

This should do what you want:

$ python script.py -h
usage: script.py [-h] [--threads] {Restart,Start} ...

positional arguments:
  {Restart,Start}

optional arguments:
  -h, --help       show this help message and exit
  --threads
$ python script.py Start -h
usage: script.py Start [-h] [--threads]

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