optparse question (python 2.6)
Peter Otten
__peter__ at web.de
Mon Aug 26 13:40:05 EDT 2013
Andy Kannberg wrote:
> Hi python-guru's,
>
> I am new to Python, coming from a long history of Unix/linux shell
> programming.
> I am creating a Python script (In Python 2.6) which should be able to
> read command line options and arguments.
> So far, I figured out how to do that with optparse. I can add options (and
> arguments ) .
> There are about 7 options that can be selected.
>
> However, I can't seem to figure out how to force that only one option is
> allowed when the script is invoked. In other words: How to restrict the
> script to accept only one of the available options ?
You have to do it manually, like in the example
http://docs.python.org/2.6/library/optparse.html#how-optparse-handles-errors
if options.a and options.b:
parser.error("options -a and -b are mutually exclusive")
which could be generalized to (untested)
option_names = ["foo", "bar", "baz", ...]
toggled_options = [name for name in option_names if getattr(options, name)]
if len(toggled_options) > 1:
s = repr(toggled_options).strip("[]")
parser.error("options %s are mutually exclusive" % s)
If you are not restricted to the standard library use
https://pypi.python.org/pypi/argparse
which was added to the stdlib in 2.7 and has "mutually exclusive groups",
see
http://docs.python.org/2/library/argparse.html#mutual-exclusion
More information about the Python-list
mailing list