重新排列Python argparse参数组

编程入门 行业动态 更新时间:2024-10-07 08:24:47
本文介绍了重新排列Python argparse参数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

本文发布于:2023-11-29 15:08:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1646751.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:排列   参数   Python   argparse

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!