Iterating over optparse options

David Goodger goodger at python.org
Wed Jun 25 09:46:23 EDT 2003


Miki Tebeka wrote:
 > Couldn't find it in the manual ...
 > Is there a way to iterate over the options optparse parser finds?

Yes, but that's not using optparse properly.

 > The rational is that I have a program with many command line
 > options.  Instead of going over all of them I'd like to set my
 > defaults and change only what is needed.

That's what optparse is meant to do, automatically.  When you
configure the parser, just set appropriate defaults for each option.
After parsing, you'll have what you want.

     parser = OptionParser()
     parser.add_option("-o", "--option", default="whatever")
     # ...add more options here...
     options, args = parser.parse_args()

Call the program with "-o something" and "options.option" will contain
"something".  Call the program with no options and "options.option"
will contain "whatever".

It may help if you don't think in terms of "options" but use
"settings" instead.  optparse handles settings, whether or not there's
a command-line option associated.

 > What I like to to is:
 > -----
 > OPTIONS = {}
 > ... <set default options>
 > parser = OptionParser()
 > ... # Configure parser
 > options, args = parser.parse_args()

If you still want to iterate over the values, you can.  "options" is
an optparse.Values instance, which contains values in its "__dict__":

     for opt, value in options.__dict__.items():
         OPTIONS[opt] = value

-- 
David Goodger    http://starship.python.net/~goodger
For hire: http://starship.python.net/~goodger/cv
Docutils: http://docutils.sourceforge.net/
(includes reStructuredText: http://docutils.sf.net/rst.html)







More information about the Python-list mailing list