如何禁止两个相互冲突的选择

Gil*_*man 4 python command-line-arguments argparse

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

arg_parser.add_argument('-c', '--clean', action='store_true')
arg_parser.add_argument('-d', '--dirty', action='store_true')
Run Code Online (Sandbox Code Playgroud)

我希望用户能够既不指定那些,也不能指定一个.

没有其他条件,它是否可以实现?

sie*_*hie 15

如何添加互斥组:

group = arg_parser.add_mutually_exclusive_group()
group.add_argument('-c', '--clean', action='store_true')
group.add_argument('-d', '--dirty', action='store_true')
Run Code Online (Sandbox Code Playgroud)

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

>>> 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
Run Code Online (Sandbox Code Playgroud)