我想构建一个程序,它有 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/