使用ArgParse结合两个不同参数的帮助消息

发布于 2025-02-11 02:25:10 字数 1069 浏览 1 评论 0原文

我正在编写一个代码,该代码必须与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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文