Python Language Parsing Command Line arguments Setting mutually exclusive arguments with argparse

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

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



Got any Python Language Question?