解析器以 2 个参数组开始,通常是 positional 和 optionals。 -h 帮助添加到 optionals。当您执行add_argument_group 时,将创建一个组(并返回给您)。它也被附加到parser._action_groups 列表中。
当您寻求帮助时 (-h) 会调用 parser.format_help()(您也可以在测试中这样做)。在argparse.py 中查找该方法。这设置了帮助消息,一步是:
# positionals, optionals and user-defined groups
for action_group in self._action_groups:
formatter.start_section(action_group.title)
formatter.add_text(action_group.description)
formatter.add_arguments(action_group._group_actions)
formatter.end_section()
因此,如果我们对parser._action_groups 列表中的项目重新排序,我们将对显示中的组重新排序。由于这是_action_groups 的唯一用途,它应该是安全且简单的。但是有些人不允许在幕后达到顶峰(查看或更改._ 属性)。
建议的解决方案是按照您希望查看的顺序创建您自己的组,并确保默认组为空(add_help=False 参数)。如果您坚持使用公共 API,这是唯一的方法。
演示:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('foo')
g1 = parser.add_argument_group('REQUIRED')
g1.add_argument('--bar', required=True)
g1.add_argument('baz', nargs=2)
print(parser._action_groups)
print([group.title for group in parser._action_groups])
print(parser.format_help())
parser._action_groups.reverse() # easy inplace change
parser.print_help()
运行结果:
1504:~/mypy$ python stack39047075.py
_actions_group 列表和标题:
[<argparse._ArgumentGroup object at 0xb7247fac>,
<argparse._ArgumentGroup object at 0xb7247f6c>,
<argparse._ArgumentGroup object at 0xb721de0c>]
['positional arguments', 'optional arguments', 'REQUIRED']
默认帮助:
usage: stack39047075.py [-h] --bar BAR foo baz baz
positional arguments:
foo
optional arguments:
-h, --help show this help message and exit
REQUIRED:
--bar BAR
baz
反转后:
usage: stack39047075.py [-h] --bar BAR foo baz baz
REQUIRED:
--bar BAR
baz
optional arguments:
-h, --help show this help message and exit
positional arguments:
foo
1504:~/mypy$
实现这一点的另一种方法是使用新的format_help 方法定义ArgumentParser 子类。在该方法中,重新排序 for action_group... 循环中使用的列表。