In my script argparse there are some arguments that will conflict if another argument of opposite kind is passed. I want to disable the --arg2
if --arg1
is already present. Currently I haven't found any way to do so.
Use a mutually exclusive group:
parser = argparse.ArgumentParser(prog='PROG')
group = parser.add_mutually_exclusive_group()
group.add_argument('--arg1')
group.add_argument('--arg2')
Only one argument in the group is allowed to be used.
Demo:
>>> import argparse
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> group = parser.add_mutually_exclusive_group()
>>> group.add_argument('--arg1')
_StoreAction(option_strings=['--arg1'], dest='arg1', nargs=None, const=None, default=None, type=None, choices=None, help=None, metavar=None)
>>> group.add_argument('--arg2')
_StoreAction(option_strings=['--arg2'], dest='arg2', nargs=None, const=None, default=None, type=None, choices=None, help=None, metavar=None)
>>> parser.parse_args(['--arg1', 'foo'])
Namespace(arg1='foo', arg2=None)
>>> parser.parse_args(['--arg2', 'bar'])
Namespace(arg1=None, arg2='bar')
>>> parser.parse_args(['--arg1', 'foo', '--arg2', 'bar'])
usage: PROG [-h] [--arg1 ARG1 | --arg2 ARG2]
PROG: error: argument --arg2: not allowed with argument --arg1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With