5

I have made a Python script that is doing a lot of actions, so it has many options, so I divided it to subparsers that also use parent parsers for common options grouping.

I want a help option that will show the help for all commands with their options, is it possible without overriding the format_help method?

I saw a similar question, but the grouping is not critical for me, I just want the options there.

For example:

general_group = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter,add_help=False)
general_group.add_argument('--threads', action='store_true', default=False)
second_group = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter,add_help=False)
second_group.add_argument('--sleep', action='store', default=60, type=int)
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
subparsers=parser.add_subparsers(dest='action')
subparsers.add_parser('Restart',parents=[general_group,second_group])
subparsers.add_parser('Start',parents=[general_group])

args = parser.parse_args()

In this case I would like that if someone runs ./script.py -h they'll see the threads option in the help.

4

1 回答 1

8

问题在于:

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

您将general_group作为父级添加到子解析器,因此主解析器不知道它们,这导致./script.py -hnot show --threads。如果您打算将其作为所有子解析器的父级,那么您应该将其作为顶级解析器父级:

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

结果是:

$ 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 --threads Start

是正确的,而:

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

因为--threads不是子解析器“继承”的。如果您还想--threads在子解析器中使用,则必须在其parents参数中指定它:

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])

这应该做你想要的:

$ 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
于 2013-02-17T13:36:26.253 回答