Setting mutually exclusive arguments with argparse

suggest change

If 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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents