Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #53495

Re: optparse question (python 2.6)

Path csiph.com!newsfeed.hal-mli.net!feeder3.hal-mli.net!newsfeed.hal-mli.net!feeder1.hal-mli.net!newsfeed.xs4all.nl!newsfeed1.news.xs4all.nl!xs4all!newsgate.cistron.nl!newsgate.news.xs4all.nl!post.news.xs4all.nl!not-for-mail
Return-Path <python-python-list@m.gmane.org>
X-Original-To python-list@python.org
Delivered-To python-list@mail.python.org
X-Spam-Status OK 0.000
X-Spam-Evidence '*H*': 1.00; '*S*': 0.00; 'python,': 0.02; 'example:': 0.03; 'url:pypi': 0.03; 'argument': 0.05; 'true,': 0.05; 'allowed.': 0.07; 'args': 0.07; 'error:': 0.07; 'modify': 0.07; 'none,': 0.07; 'parser': 0.07; '[],': 0.09; '__init__': 0.09; 'arguments': 0.09; 'exit': 0.09; 'option,': 0.09; 'optparse': 0.09; 'received:80.91': 0.09; 'received:80.91.229': 0.09; 'received:gmane.org': 0.09; 'received:list': 0.09; 'restriction': 0.09; 'works.': 0.09; 'subject:question': 0.10; 'python': 0.11; '"o"': 0.16; '"s"': 0.16; '**kwargs)': 0.16; '-1,': 0.16; '-o,': 0.16; '[name': 0.16; 'andy': 0.16; 'argument.': 0.16; 'boolean': 0.16; 'conflicting': 0.16; 'great!': 0.16; 'received:80.91.229.3': 0.16; 'received:dip0.t-ipconnect.de': 0.16; 'received:plane.gmane.org': 0.16; 'received:t-ipconnect.de': 0.16; 'selected.': 0.16; 'supplied': 0.16; 'subject:python': 0.16; 'wrote:': 0.18; 'value.': 0.19; 'not,': 0.20; 'example': 0.22; 'import': 0.22; 'print': 0.22; 'header:User-Agent:1': 0.23; 'error': 0.23; 'exists': 0.24; 'options': 0.25; 'mention': 0.26; 'skip:" 30': 0.26; 'this:': 0.26; 'second': 0.26; 'defined': 0.27; 'skip:" 20': 0.27; 'header:X-Complaints-To:1': 0.27; 'tried': 0.27; 'point': 0.28; 'host': 0.29; "doesn't": 0.30; 'direction': 0.30; "i'm": 0.30; 'code': 0.31; "skip:' 10": 0.31; '"",': 0.31; 'file': 0.32; 'option': 0.32; 'run': 0.32; 'url:python': 0.33; '(most': 0.33; 'third': 0.33; 'subject: (': 0.35; 'but': 0.35; 'add': 0.35; 'there': 0.35; 'version': 0.36; '2.6': 0.36; 'found.': 0.36; 'options:': 0.36; "i'll": 0.36; 'url:org': 0.36; 'should': 0.36; 'so,': 0.37; 'skip:- 20': 0.37; 'list': 0.37; 'skip:o 20': 0.38; 'checks': 0.38; 'url:library': 0.38; 'skip:[ 10': 0.38; 'to:addr :python-list': 0.38; 'skip:- 10': 0.38; 'recent': 0.39; 'does': 0.39; 'skip:. 10': 0.39; 'to:addr:python.org': 0.39; 'skip:p 20': 0.39; 'received:org': 0.40; 'above,': 0.60; 'skip:o 30': 0.61; 'first': 0.61; 'act': 0.63; 'show': 0.63; 'name': 0.63; 'more': 0.64; 'here': 0.66; 'default': 0.69; 'skip:r 30': 0.69; 'exclusive': 0.81; "'true'": 0.84; 'conflicts': 0.84
X-Injected-Via-Gmane http://gmane.org/
To python-list@python.org
From Peter Otten <__peter__@web.de>
Subject Re: optparse question (python 2.6)
Date Mon, 02 Sep 2013 17:33:53 +0200
Organization None
References <CADDfdi60cYjd4kiZXPSiRpYbEgmPeNnG5Myhx1vRMMW2fm-Vbg@mail.gmail.com>
Mime-Version 1.0
Content-Type text/plain; charset="ISO-8859-1"
Content-Transfer-Encoding 7Bit
X-Gmane-NNTP-Posting-Host p50849b98.dip0.t-ipconnect.de
User-Agent KNode/4.7.3
X-BeenThere python-list@python.org
X-Mailman-Version 2.1.15
Precedence list
List-Id General discussion list for the Python programming language <python-list.python.org>
List-Unsubscribe <http://mail.python.org/mailman/options/python-list>, <mailto:python-list-request@python.org?subject=unsubscribe>
List-Archive <http://mail.python.org/pipermail/python-list/>
List-Post <mailto:python-list@python.org>
List-Help <mailto:python-list-request@python.org?subject=help>
List-Subscribe <http://mail.python.org/mailman/listinfo/python-list>, <mailto:python-list-request@python.org?subject=subscribe>
Newsgroups comp.lang.python
Message-ID <mailman.495.1378136033.19984.python-list@python.org> (permalink)
Lines 139
NNTP-Posting-Host 2001:888:2000:d::a6
X-Trace 1378136033 news.xs4all.nl 15936 [2001:888:2000:d::a6]:50900
X-Complaints-To abuse@xs4all.nl
Xref csiph.com comp.lang.python:53495

Show key headers only | View raw


Andy Kannberg wrote:

> I tried with the example Peter gave me, and it works. But only when the
> options are boolean. At least, that is my conclusion with experimenting.
> I'll elaborate:
> 
> The code to create 'mutually exclusive options':
> 
> option_names =  [ "l",  "o" , "s" ]
> toggled_options = [name for name in option_names if getattr(opts, name)]
> if len(toggled_options) > 1:
>   s = repr(toggled_options).strip("[]")
>   parser.error("options %s are mutually exclusive" % s)

This doesn't actually create mutually exclusive options, it just checks if 
there are conflicting options after they are parsed, and exists with an 
error message when conflicts are found.

> The options:
> 
> parser = optparse.OptionParser()
> parser.add_option('-l', help='Show optionset list',  dest='l',
> action='store_true'  )
> parser.add_option('-o', help='Show content of optionset ', dest='o',
> action='store')
> parser.add_option('-s', help='Set optionset for a host', dest='s',
> action='store' , nargs=2)
> 
> The first option, -l, doesn't require an argument
> The second option, -o, does require one argument.
> The third option, -s does require 2 arguments.
> 
> I need to add 4 more options, which all need one or more arguments.
> 
> Now, when I run the program with the  options defined as above, everything
> works, except, the 'mutually exclusive' part. Because only the -l option
> is set to 'true' when selected. When I modify the options to this:
> 
> parser = optparse.OptionParser()
> parser.add_option('-l', help='Show optionset list',  dest='l',
> action='store_true'  )
> parser.add_option('-o', help='Show content of optionset ', dest='o',
> action='store_true')
> parser.add_option('-s', help='Set optionset for a host', dest='s',
> action='store_true' , nargs=2)
> 
> I get this error:
> 
> # ./listopt3.py -o -l
> Traceback (most recent call last):
>   File "./listopt3.py", line 8, in <module>
>     parser.add_option('-s', help='Set optionset for a host', dest='s',
> action='store_true' , nargs=2)
>   File "/usr/lib64/python2.6/optparse.py", line 1012, in add_option
>     option = self.option_class(*args, **kwargs)
>   File "/usr/lib64/python2.6/optparse.py", line 577, in __init__
>     checker(self)
>   File "/usr/lib64/python2.6/optparse.py", line 706, in _check_nargs
>     self)
> optparse.OptionError: option -s: 'nargs' must not be supplied for action
> 'store_true'
> 
> So, apparanly, using boolean AND arguments isn't allowed.
> I'm still learning Python, so if someone can point me in the right
> direction would be great!

You don't need the action="store_true" for every option, only for those that 
act as a flag, i. e. are present or not, but don't carry a value. 

Here is a working example:

$ cat optparse_mutually_exclusive.py
import optparse

parser = optparse.OptionParser()
parser.add_option("-l", "--list-optionsets", help="Show optionset list", 
action="store_true")
parser.add_option("-o", "--show-options", help="Show content of optionset")
parser.add_option("-s", "--set-options", help="Set optionset for a host", 
nargs=2)

options, args = parser.parse_args()

option_names = ["list_optionsets", "show_options", "set_options"]
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)

print options


Let's run it a few times:

$ python2.6 optparse_mutually_exclusive.py -h
Usage: optparse_mutually_exclusive.py [options]

Options:
  -h, --help            show this help message and exit
  -l, --list-optionsets
                        Show optionset list
  -o SHOW_OPTIONS, --show-options=SHOW_OPTIONS
                        Show content of optionset
  -s SET_OPTIONS, --set-options=SET_OPTIONS
                        Set optionset for a host
$ python2.6 optparse_mutually_exclusive.py --list-optionsets
{'list_optionsets': True, 'show_options': None, 'set_options': None}
$ python2.6 optparse_mutually_exclusive.py --list-optionsets --show-options
Usage: optparse_mutually_exclusive.py [options]

optparse_mutually_exclusive.py: error: --show-options option requires an 
argument
$ python2.6 optparse_mutually_exclusive.py --show-options foo
{'list_optionsets': None, 'show_options': 'foo', 'set_options': None}
$ python2.6 optparse_mutually_exclusive.py --show-options foo -s bar baz
Usage: optparse_mutually_exclusive.py [options]

optparse_mutually_exclusive.py: error: options 'show_options', 'set_options' 
are mutually exclusive
$ python2.6 optparse_mutually_exclusive.py foo -s bar baz
{'list_optionsets': None, 'show_options': None, 'set_options': ('bar', 
'baz')}


I should mention one important restriction with this approach: the default 
value must be "falsy" like None, [], "", 0, and the value provided by the 
user must be "truish" like -1, 42.0, "foo", ["a", "b"].

Also, ceterum censeo ;) -- there is a version of argparse available for 
download on 

https://pypi.python.org/pypi/argparse

that should work with Python 2.6 and offers a better approach, see

http://docs.python.org/2/library/argparse.html#sub-commands

for the documentation.

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: optparse question (python 2.6) Peter Otten <__peter__@web.de> - 2013-09-02 17:33 +0200

csiph-web