
I can sympathize with Mark, I have nearly the same code in every script I write. I once wrote a nice (IMO) class for doing all the common things I do with c.l. args, but I can't seem to dig it up at the moment. The idea was basically to have a base class that had all the machinery, while derived classes included specially named methods that did the app-specific option handling. It knew whether the method took 1 or zero arguments (not including self), glommed up the shortarg string and longarg list (with appropriate `:' and `=' thrown in), then parsed the args, dispatching to the handlers, e.g.: class MyOptions(getopt.Options): def handle_a(self): self.alpha = 1 handle_alpha = handle_a def handle_b(self, arg): self.beta = arg handle_beta = handle_b def handle_i(self, arg): try: self.integer = int(arg) except ValueError: self.usage() handle_integer = handle_i and could be used like so: #! /usr/bin/env python # # ... opts = MyOptions(sys.argv[1:], usage=__doc__ % globals()) if opts.alpha: do_my_alpha_thang() if opts.integer = 1: do_something_else() for file in opts.leftoverargs: process_file(file) While I liked this a lot, I seem to remember showing it to Guido, receiving the expected scoffing. So now, I just cut and paste the opt parsing stuff into every script I write :) I think it might be nice to add such a base class to the standard getopt module. -Barry