如何禁止两个冲突的选项 [英] How to forbid two conflicting options

查看:30
本文介绍了如何禁止两个冲突的选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法向 Python 的 ArgumentParser 指定两个可选标志冲突?

arg_parser.add_argument('-c', '--clean', action='store_true')arg_parser.add_argument('-d', '--dirty', action='store_true')

我希望用户能够不指定任何一个,或者只指定一个.

是否可以在没有其他条件的情况下实现?

解决方案

如何添加一个 互斥组:

group = arg_parser.add_mutually_exclusive_group()group.add_argument('-c', '--clean', action='store_true')group.add_argument('-d', '--dirty', action='store_true')

有了这个,我得到了以下行为:

<预><代码>>>>arg_parser.parse_args(['--clean'])命名空间(干净=真,脏=假)>>>arg_parser.parse_args(['--dirty'])命名空间(干净=假,脏=真)>>>arg_parser.parse_args(['--dirty','--clean'])用法:PROG [-h] [-c |-d] PROG:错误:参数 -c/--clean:参数 -d/--dirty 不允许

Is there a way to specify to Python's ArgumentParser that two optional flags are conflicting?

arg_parser.add_argument('-c', '--clean', action='store_true')
arg_parser.add_argument('-d', '--dirty', action='store_true')

I want the user to be able to specify either none of those, or only one.

Is it achievable without further conditions?

解决方案

How about adding a mutually exclusive group:

group = arg_parser.add_mutually_exclusive_group()
group.add_argument('-c', '--clean', action='store_true')
group.add_argument('-d', '--dirty', action='store_true')

with this I get the following behaviour:

>>> arg_parser.parse_args(['--clean']) 
Namespace(clean=True, dirty=False)
>>> arg_parser.parse_args(['--dirty']) 
Namespace(clean=False, dirty=True)
>>> arg_parser.parse_args(['--dirty','--clean']) 
usage: PROG [-h] [-c | -d] PROG: error: argument -c/--clean: not allowed with argument -d/--dirty

这篇关于如何禁止两个冲突的选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆