Question of Optionparse
Peter Otten
__peter__ at web.de
Tue Nov 30 03:23:27 EST 2004
Pekka Niiranen wrote:
> 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
More information about the Python-list
mailing list