Setting mutually exclusive arguments with argparse
suggest changeIf you want two or more arguments to be mutually exclusive, use 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')
parser.parse_args()
If the script is sample.py and you pass both --foo and --bar, it exits with:
usage: sample.py [-h] [-f FOO | -b BAR]
sample.py: error: argument -b/--bar: not allowed with argument -f/--foo
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents