ArgumentParser.add_mutually_exclusive_group(required=False)
Create a mutually exclusive group. argparse
will make sure that only one of the arguments in the mutually exclusive group was present on the command line:
1 2 3 4 5 6 7 8 9 10 11 | >>> parser = argparse.ArgumentParser(prog= 'PROG' ) >>> group = parser.add_mutually_exclusive_group() >>> group.add_argument( '--foo' , action= 'store_true' ) >>> group.add_argument( '--bar' , action= 'store_false' ) >>> parser.parse_args([ '--foo' ]) Namespace(bar=True, foo=True) >>> parser.parse_args([ '--bar' ]) Namespace(bar=False, foo=False) >>> parser.parse_args([ '--foo' , '--bar' ]) usage: PROG [-h] [--foo | --bar] PROG: error: argument --bar: not allowed with argument --foo |
The add_mutually_exclusive_group()
method also accepts a required argument, to indicate that at least one of the mutually exclusive arguments is required:
1 2 3 4 5 6 7 | >>> parser = argparse.ArgumentParser(prog= 'PROG' ) >>> group = parser.add_mutually_exclusive_group(required=True) >>> group.add_argument( '--foo' , action= 'store_true' ) >>> group.add_argument( '--bar' , action= 'store_false' ) >>> parser.parse_args([]) usage: PROG [-h] (--foo | --bar) PROG: error: one of the arguments --foo --bar is required |
Note that currently mutually exclusive argument groups do not support the title and description arguments of add_argument_group()
.
Please login to continue.