分析器开始了与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...
循环中使用的列表。