Question of Optionparse

P

Pekka Niiranen

Hi,

How can I STOP Optionparse to process boolean
value as parameter. See this:
>>> parser = optparse.OptionParser()
>>> parser.add_option("-x",dest='xxx', action="store_true",help="xxx")
>>> parser.add_option("-r",dest='root',help="directory",type="string")
>>> args = ["-r", "d:", "-x"]
>>> parser.parse_args(args)
(<Values at 0x13bbbc0: {'xxx': True, 'root': 'd:'}>, [])

Last line is correct: boolean 'xxx' gets set 'True'
and parameter 'root' to 'd:'

However when value is NOT given for '-r' but '-x' exists:
>>> args = ["-r", "-x"]
>>> parser.parse_args(args)
(<Values at 0x13ccf80: {'xxx': None, 'root': '-x'}>, [])

This is BS: I expected 'root' to be None and 'xxx' to be 'True'.
How can I make it so?

Another question: Is there a way to store options
directly into user defined dictionary without assignment
like this:

my_environment_values = {}
(options, args) = parser.parse_args()
environment_values["xxx"] = options.xxx

-pekka-
 
P

Peter Otten

Pekka said:
How can I STOP Optionparse to process boolean
value as parameter. See this:
parser = optparse.OptionParser()
parser.add_option("-x",dest='xxx', action="store_true",help="xxx")
parser.add_option("-r",dest='root',help="directory",type="string")
args = ["-r", "d:", "-x"]
parser.parse_args(args)
(<Values at 0x13bbbc0: {'xxx': True, 'root': 'd:'}>, [])

Last line is correct: boolean 'xxx' gets set 'True'
and parameter 'root' to 'd:'

However when value is NOT given for '-r' but '-x' exists:
args = ["-r", "-x"]
parser.parse_args(args)
(<Values at 0x13ccf80: {'xxx': None, 'root': '-x'}>, [])

This is BS: I expected 'root' to be None and 'xxx' to be 'True'.
How can I make it so?

I think you need a callback option.
Another question: Is there a way to store options
directly into user defined dictionary without assignment
like this:

my_environment_values = {}
(options, args) = parser.parse_args()
environment_values["xxx"] = options.xxx

environment_values.update(options.__dict__)

Full example:

import optparse

def callback(option, opt, value, parser):
rargs = parser.rargs
if rargs and not rargs[0].startswith("-"):
parser.values.root = rargs.pop(0)
else:
parser.values.root = "<no value provided>"

parser = optparse.OptionParser()
parser.add_option("-x", "--xtra-terrestrial", action="store_true")
parser.add_option("-r", "--root", action="callback", callback=callback)

options, args = parser.parse_args()

environment = {}
environment.update(options.__dict__)

print environment

Peter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,212
Messages
2,571,101
Members
47,695
Latest member
KayleneBee

Latest Threads

Top