我正在使用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参数组
发布评论