python - 使用 argparse 创建互包参数

标签 python argparse

我想构建一个程序,它有 2 个相互包含的参数和 2 个不依赖于前两个的参数。像这样的事情:

consume [--count n] | show | clear

其中“consume”和“--count”相互依赖,即,没有“consume”“--count”将抛出错误“show”和“clear”不依赖于第一个消耗并且--计数。

编辑: show 和clear 是可选参数

到目前为止,这是我能做的:

import argparse
parser = argparse.ArgumentParser()
group = argparse.ArgumentParser(usage='%(prog)s [consume [--count]]')
group.add_argument('consume', help='mutually inclusive with count')
group.add_argument('--count', type = int, help='get the count n')

parser.add_argument('show', help='show the messages')
parser.add_argument('clear', help='clear messages from db')

args = group.parse_args()
args1 = parser.parse_args()

if args.count and not args.consume:
    parser.error('the following arguments are required: consume')
else:
    print(args.count)
    print(args1.show)
    print(args1.clear)

因此,当运行命令时,无需消耗:

[filename] --count 7 show clear

我收到以下错误:

unrecognized arguments: clear

有人可以帮助我使这些论点相互包容,并使其他论点不依赖于它们吗?

最佳答案

你可以尝试这样的事情......

添加一个 MutuallyInclusiveArgumentError 异常子类,然后将参数拆分为参数组,并在解析完成后检查是否有错误。

import argparse
import sys
class MutuallyInclusiveArgumentError(Exception):
    pass

parser = argparse.ArgumentParser(sys.argv[0])
subs = parser.add_argument_group("mutually inclusive")
subs.add_argument('--consume', help='mutually inclusive with count', action='store_true')
subs.add_argument('--count', type = int, help='get the count n')
parser.add_argument('--show', help='show the messages', action='store_true')
parser.add_argument('--clear', help='clear messages from db', action='store_true')


args = parser.parse_args()
if args.count and args.consume is False:
    raise MutuallyInclusiveArgumentError("--count option must be used with the --consume option" )



print(vars(args))

帮助消息如下所示

usage: {progname} [-h] [--consume] [--count COUNT] [--show] [--clear]

options:
  -h, --help     show this help message and exit
  --show         show the messages
  --clear        clear messages from db

mutually inclusive:
  --consume      mutually inclusive with count
  --count COUNT  get the count n


关于python - 使用 argparse 创建互包参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72311036/

相关文章:

python - 我该如何着手只打印大写锁定的名字的第一个字母以及以下内容?

python - 为什么这个简单的 numpy 乘法运算会引发 "invalid number of arguments"错误?

python - 如何在不打补丁的情况下本地化 Python 的 argparse 模块?

python - Argparse 单元测试 : Suppress the help message

python - 如何验证传递参数的总数?

python - 如何更改 python 字典的 __setattr__ 的行为?

Python 分组显示列

python - 在 Django 中,如何使用 iexact 检查项目是否不区分大小写匹配?

python - argparse - 使用特定参数重现 "--help"参数的行为

python - 如何在 Python 2.6 中获取 argparse?