optparse question (python 2.6)

Peter Otten __peter__ at web.de
Mon Sep 2 11:33:53 EDT 2013


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.




More information about the Python-list mailing list