Iterating command switches from a data file - have a working solution but it seems inefficient

bruno at modulix onurb at xiludom.gro
Thu Apr 13 06:45:23 EDT 2006


News wrote:
> bruno at modulix wrote:
> 
>>News wrote:
>>
>>>Hi everyone,
>>>
>>>My goal is to pull command switches/options from a file and then assign
>>>the values to select variables which would eventually be included in a
>>>class object.
>>>
>>>The data file looks something like this but the switches could be in any
>>>order and not all may be used.
>>>
>>>-m quemanager -s server -p port -k key -o object -c 20 -t test at email.com
>>
>>Have you looked at optparse ?
>>
> 
> I have.
> 
> In the interactive version of the code, I use:
> 
>     #
>     # Parse command line options and automatically build help/usage
>     #
>     parser = OptionParser()
> 
>     parser.add_option("-q", "--quiet",
>                     action="store_false", dest="verbose", default=1,
>                     help="don't print status messages to stdout")
>     parser.add_option("-m", dest="qmanager",
>                     help="Queue Manager to inquire against")
>     parser.add_option("-s", dest="host",
>                     help="Host the que manager resides on")
>     parser.add_option("-p", dest="port",
>                     help="Port queue manager listens on"),
>     parser.add_option("-o", dest="object",
>                     help="Queue object being inquired on"),
>     parser.add_option("-k", dest="key",
>                     help="object attribute to be inquired about"),
>     parser.add_option("-t", type="string",dest="mto",
>                     help="e-mail address the report will go to"),
>     parser.add_option("-d", action="store_false",dest="report",
>                     help="optional switch - enabling this sends output
> to e-mail")
>     (options, args) = parser.parse_args()
> 

So why do you inflict yourself the pain of rewriting all the parsing etc???

> The module optparse seemed to be aimed at reading from commandline
> versus pulling attributes from a read line.

http://www.python.org/doc/2.4.2/lib/optparse-parsing-arguments.html:
"""
The whole point of creating and populating an OptionParser is to call
its parse_args() method:

(options, args) = parser.parse_args(args=None, options=None)

where the input parameters are

args
    the list of arguments to process (sys.argv[1:] by default)
"""

what about something like :

 line = myfile.readline()
 options = parser.parse_args(line.split())

But what, if you prefer to rewrite (and maintain) a custom parser doing
exactly the same thing, please do !-)

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list