使用ArgParse结合两个不同参数的帮助消息
我正在编写一个代码,该代码必须与Python-3.8+兼容,并且具有CLI。在这个CLI中,我有一个可选的论点,应该是布尔国旗。我将其定义为这样:
import argparse
parser = argparse.ArgumentParser(description="test parser")
group = parser.add_mutually_exclusive_group(required=False)
group.add_argument('--feature', action='store_true', dest='feature', help="help 1")
group.add_argument('--no-feature', action='store_false', dest='feature', help="help 2")
group.set_defaults(feature=True)
命令的行为是按预期的,但是我的问题在于帮助消息。每当显示出来时,它看起来都这样:
usage: test [--feature | --no-feature]
optional arguments:
-h, --help show this help message and exit
--feature help 1
--no-feature help 2
我应该如何修改此代码,因此帮助消息的输出是类似于使用Python-3.9+ action = argparse.booleanoptionalactional 在python3.8+的同时保持兼容?
我期望的输出应该看起来像这样:
usage: test [--feature | --no-feature]
optional arguments:
-h, --help show this help message and exit
--feature, --no-feature help 1 & 2
I'm writing a code that is required to be compatible with Python-3.8+, and it have a CLI. In this CLI I have an optional argument that is supposed to be a boolean flag. I define it as such:
import argparse
parser = argparse.ArgumentParser(description="test parser")
group = parser.add_mutually_exclusive_group(required=False)
group.add_argument('--feature', action='store_true', dest='feature', help="help 1")
group.add_argument('--no-feature', action='store_false', dest='feature', help="help 2")
group.set_defaults(feature=True)
The command behave as expected, however, my problem lies with the help message. Whenever it shows up, it would look like this:
usage: test [--feature | --no-feature]
optional arguments:
-h, --help show this help message and exit
--feature help 1
--no-feature help 2
How should I modify this code so the output of the help message is instead something like the help message we get when using python-3.9+ action=argparse.BooleanOptionalAction
while remaining compatible for Python3.8+ ?
The output I expect should look like this:
usage: test [--feature | --no-feature]
optional arguments:
-h, --help show this help message and exit
--feature, --no-feature help 1 & 2
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论