Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #53010 > unrolled thread
| Started by | Peter Otten <__peter__@web.de> |
|---|---|
| First post | 2013-08-26 19:40 +0200 |
| Last post | 2013-08-26 19:40 +0200 |
| Articles | 1 — 1 participant |
Back to article view | Back to comp.lang.python
This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by
below is the oldest one visible, not the original post.
Re: optparse question (python 2.6) Peter Otten <__peter__@web.de> - 2013-08-26 19:40 +0200
| From | Peter Otten <__peter__@web.de> |
|---|---|
| Date | 2013-08-26 19:40 +0200 |
| Subject | Re: optparse question (python 2.6) |
| Message-ID | <mailman.243.1377538796.19984.python-list@python.org> |
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 top | Article view | comp.lang.python
csiph-web