重新排序 Python argparse 参数组 [英] Reorder Python argparse argument groups
问题描述
我正在使用 argparse
并且我有一个自定义参数组 required arguments
.有什么方法可以更改帮助消息中参数组的顺序?我认为在可选参数之前添加必需参数更合乎逻辑,但还没有找到任何文档或问题来提供帮助.
I'm using argparse
and I have a custom argument group required arguments
. Is there any way to change the order of the argument groups in the help message? I think it is more logical to have the required arguments before optional arguments, but haven't found any documentation or questions to help.
例如,改变这个:
usage: foo.py [-h] -i INPUT [-o OUTPUT]
Foo
optional arguments:
-h, --help show this help message and exit
-o OUTPUT, --output OUTPUT
Output file name
required arguments:
-i INPUT, --input INPUT
Input file name
对此:
usage: foo.py [-h] -i INPUT [-o OUTPUT]
Foo
required arguments:
-i INPUT, --input INPUT
Input file name
optional arguments:
-h, --help show this help message and exit
-o OUTPUT, --output OUTPUT
Output file name
(示例取自这个问题)
推荐答案
您可以考虑添加显式可选参数组:
You might consider adding an explicit optional arguments group:
import argparse
parser = argparse.ArgumentParser(description='Foo', add_help=False)
required = parser.add_argument_group('required arguments')
required.add_argument('-i', '--input', help='Input file name', required=True)
optional = parser.add_argument_group('optional arguments')
optional.add_argument("-h", "--help", action="help", help="show this help message and exit")
optional.add_argument('-o', '--output', help='Output file name', default='stdout')
parser.parse_args(['-h'])
您可以将帮助操作移动到您的可选组中作为这里描述:移动帮助"到 python argparse 中的不同参数组
You can move the help action to your optional group as described here: Move "help" to a different Argument Group in python argparse
如您所见,代码生成了所需的输出:
As you can see, the code produces the required output:
usage: code.py -i INPUT [-h] [-o OUTPUT]
Foo
required arguments:
-i INPUT, --input INPUT
Input file name
optional arguments:
-h, --help show this help message and exit
-o OUTPUT, --output OUTPUT
Output file name
这篇关于重新排序 Python argparse 参数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!