Reputation: 6550
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?
Upvotes: 12
Views: 4727
Reputation: 7553
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
Upvotes: 29