gpt4 book ai didi

python - 重新排序 Python argparse 参数组

转载 作者:太空狗 更新时间:2023-10-29 20:10:36 26 4
gpt4 key购买 nike

我正在使用 argparse 并且我有一个自定义参数组 required arguments。有什么方法可以更改帮助消息中参数组的顺序吗?我认为在可选参数之前添加必需参数更符合逻辑,但没有找到任何文档或问题来提供帮助。

例如,改变这个:

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

(示例取自 this question )

最佳答案

您可以考虑添加一个显式可选参数组:

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

您可以将帮助操作移动到您的可选组此处描述: Move "help" to a different Argument Group in python argparse

如您所见,代码生成了所需的输出:

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 - 重新排序 Python argparse 参数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39047075/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com