Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #53010
| From | Peter Otten <__peter__@web.de> |
|---|---|
| Subject | Re: optparse question (python 2.6) |
| Date | 2013-08-26 19:40 +0200 |
| Organization | None |
| References | <CADDfdi7S0+9km=SiQ4ZZ9q3YFj0DxFKbRdPFf5bKz44E_rykdg@mail.gmail.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.243.1377538796.19984.python-list@python.org> (permalink) |
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
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: optparse question (python 2.6) Peter Otten <__peter__@web.de> - 2013-08-26 19:40 +0200
csiph-web