[Tutor] Groups of mutually exclusive options

rail shafigulin rail.shafigulin at gmail.com
Mon Apr 21 23:05:49 CEST 2014


Does anybody know if there is a way to specify groups of mutually exclusive
options using argparse module?

Currently argpase allows to specify mutually exclusive options in the
following way
(taken from
https://docs.python.org/release/3.4.0/library/argparse.html#argparse.ArgumentParser.add_mutually_exclusive_group
)

>>> 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

What I need is a way to specify groups of mutually exclusive options.  In
other words

>>> parser = argparse.ArgumentParser(prog='PROG')>>> group1 = parser.add_argument_group()>>> group2 = parser.add_argument_group()>>> group1.add_argument('--foo', action='store_true')>>> group1.add_argument('--bar1', action='store_false')>>> group2.add_argument('--foo2', action = 'store_true')
>>> group2.add_argument('--bar2', action = 'store_false')
>>> mutually_exclusive_group = parser.add_mutually_exclusive_argument_group()
>>> mutually_exclusive_group.add_group(group1)
>>> mutually_exclusive_group.add_group(group2)>>> parser.parse_args(['--foo1', '--bar1', '--bar2'])usage: PROG [-h] [--foo1, --bar1] | [--foo2, --bar2]PROG: error: argument --foo1 or bar1 not allowed with argument --foo2 or bar2
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20140421/185f9fb6/attachment.html>


More information about the Tutor mailing list