couple of optparse questions

Eyal Teutsch eyal.teutsch at gmail.com
Thu Apr 24 07:47:52 CEST 2008


I have a bunch of command line scripts which I would like them to partially
share command line options. For the sake of example, let's say I have the
following 2 scripts:

monitor_io.py - accepts 'interval' and 'disk' arguments: monitor_io.py -i 30
-d disk1
monitor_processes.py - accepts 'interval' and '# of procesess' arguments:
monitor_processes.py -i 15 -n 8

So what I would like to do, is to have a shared command line parser (let's
call it parser.py) that would selectively use the parser.add_option calls
according to the arguments that were passed to it when it was instantiated
by the above command line scripts.
So, in monitor_io.py, the parser would be instantiated as follows:
parsamon = parse(['interval', 'disk'])

and in parser.py, I would have a dictionary of all possible options:

self.options['interval'] ='"-c", action="callback", dest="interval",
type="int", callback=self.verify_type, callback_kwargs={"action":"int"},
help="the execution interval"' # does not work

and then selectively add specific options to the parser according to the
arguments passed to parser.py, for instance:

parser.add_option(self.options['interval'])

The above though wouldn't work as what seems to me a quotation error. The
following, would actually work:
self.options['interval']='-c'

while this one here would not:
self.options['interval']='-c, action="store_true"' # does not work

it terminates with the following error:
optparse.OptionError: invalid long option string '-c, action="store_true"':
must start with --, foll
owed by non-dash

It would accept though a double-dash (which isn't what I want):
self.options['interval']='--c, action="store_true"' # works

but then again, the full option using a double dash, would not work:
self.options['interval']='"--c", action="callback", dest="interval",
type="int", callback=self.verify_type, callback_kwargs={"action":"int"},
help="the execution interval"'  # does not work

optparse.OptionError: invalid long option string '"--c", action="callback",
dest="mint_interval", ty
pe="int", callback=self.verify_type, callback_kwargs={"action":"int"},
help="the mint interval"': mu
st start with --, followed by non-dash

So, my first question is how to accomplish the above task?

My second question is that I found the fact that optparse returns the values
as properties of the object rather than returning a dictionary with all
parsed options a bit inconvenient, as the latter approach would offer
convenient ways to iterate/verify the parsed arguments returned. Any
thoughts on this?

Thanks..
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20080424/49b4751d/attachment.html>


More information about the Python-list mailing list