用Argparse创建相互包容性论点
我想构建一个具有2个相互包容性的ARG和2个不依赖前两个的程序。类似的内容:
consume [--count n] | show | clear
“消费”和“ - 计数”彼此取决于彼此,即没有“消耗” - 计数“会丢弃错误” show'和'clear'和'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
有人可以帮助我做出互包容性的参数和其他不依赖于它们的参数吗?
I want to build a program that has 2 mutually inclusive args and 2 that are not dependent on the first two. Something like this:
consume [--count n] | show | clear
where 'consume' and '--count' are dependent on each other i.e, without 'consume' '--count' will throw an error 'show' and 'clear' do not depend on the first consume and --count.
Edit:
show and clear are optional arguments
Here's what I was able to do till now:
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)
So when the run the command, without consume:
[filename] --count 7 show clear
I get the following error:
unrecognized arguments: clear
Can someone help me with making the arguments mutually inclusive and other arguments not dependent on them?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以尝试这样的事情...
添加
mutalalyInclusiveargumentError
异常子类,然后在参数组中拆分参数,并在完成解析后检查错误。帮助消息看起来像这样
You could try something like this...
Add a
MutuallyInclusiveArgumentError
Exception subclass, then split the arguments in an argument group, and check for errors after parsing has been completed.the help message looks like this