optparse: best way

Peter Otten __peter__ at web.de
Tue Jun 8 06:31:42 EDT 2010


hiral wrote:

> Hi,
> 
> I am using optparser to do following...
> 
> Command syntax:
> myscript -o[exension] other_arguments
>     where; extension can be 'exe', 'txt', 'pdf', 'ppt' etc.
> 
> 
> Now to parse this, I am doing following...
> 
> parser.add_option("-oexe', dest=exe_file...)
> parser.add_option("-otxt', dest=txt_file...)
> parser.add_option("-opdf', dest=pdf_file...)
> parser.add_option("-oppt', dest=ppt_file...)
> 
> The above way is the most simple way to parser options.
> Can you please suggest any other best way / optimized way to parse
> these kind of options.
> 
> Thank you in advance.

You could limit the value for the -o option with

parser.add_option("-o", dest="ext", choices="exe txt pdf ppt".split())

and do the actual work outside the OptionParser.

options, args = parser.parse_args()

def process_exe():
    # whatever

actions = {"exe": process_exe, ...}
actions[options.ext]()

Peter



More information about the Python-list mailing list