If you want two or more arguments to be mutually exclusive. You can use the function argparse.ArgumentParser.add_mutually_exclusive_group()
. In the example below, either foo or bar can exist but not both at the same time.
import argparse
parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group()
group.add_argument("-f", "--foo")
group.add_argument("-b", "--bar")
args = parser.parse_args()
print "foo = ", args.foo
print "bar = ", args.bar
If you try to run the script specifying both --foo
and --bar
arguments, the script will complain with the below message.
error: argument -b/--bar: not allowed with argument -f/--foo