Re: Iterating over optparse options

Discussion in 'Python' started by David Goodger, Jun 25, 2003.

  1. 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)
    David Goodger, Jun 25, 2003
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Gregory (Grisha) Trubetskoy

    Required options in optparse

    Gregory (Grisha) Trubetskoy, Oct 4, 2003, in forum: Python
    Replies:
    0
    Views:
    409
    Gregory (Grisha) Trubetskoy
    Oct 4, 2003
  2. Steven Bethard
    Replies:
    0
    Views:
    382
    Steven Bethard
    May 10, 2006
  3. Rocky Zhou
    Replies:
    3
    Views:
    296
    Steven Bethard
    Mar 18, 2007
  4. Omari Norman

    Re: optparse - required options

    Omari Norman, Aug 23, 2007, in forum: Python
    Replies:
    2
    Views:
    416
    Steve Holden
    Aug 24, 2007
  5. carl
    Replies:
    5
    Views:
    2,318
    James Kanze
    Nov 25, 2009
Loading...

Share This Page