Website hosting service by Active-Venture.com
  

 Back to Index


6.20.3.1 Creating and populating the parser

There are several ways to populate the parser with options. One way is to pass a list of Options to the OptionParser constructor:

from optparse import OptionParser, make_option
[...]
parser = OptionParser(option_list=[
    make_option("-f", "--filename",
                action="store", type="string", dest="filename"),
    make_option("-q", "--quiet",
                action="store_false", dest="verbose")])

(make_option() is a factory function for generating Option objects.)

For long option lists, it may be more convenient/readable to create the list separately:

option_list = [make_option("-f", "--filename",
                           action="store", type="string", dest="filename"),
               [... more options ...]
               make_option("-q", "--quiet",
                           action="store_false", dest="verbose")]
parser = OptionParser(option_list=option_list)

Or, you can use the add_option() method of OptionParser to add options one-at-a-time:

 

parser = OptionParser()
parser.add_option("-f", "--filename",
                  action="store", type="string", dest="filename")
parser.add_option("-q", "--quiet",
                  action="store_false", dest="verbose")

This method makes it easier to track down exceptions raised by the Option constructor, which are common because of the complicated interdependencies among the various keyword arguments. (If you get it wrong, optparse raises OptionError.)

add_option() can be called in one of two ways:

 

  • pass it an Option instance (as returned by make_option())
  • pass it any combination of positional and keyword arguments that are acceptable to make_option() (i.e., to the Option constructor), and it will create the Option instance for you (shown above).
 

  

 

© 2002-2004 Active-Venture.com Webhosting Service

 

Disclaimer: This documentation is provided only for the benefits of our hosting customers.
For authoritative source of the documentation, please refer to http://python.org/doc/

 

Active-Domain.com offers domain name registration, domain name transfer and domain search services  

Cheap domain registration : Register domain name or buy domain name, including free domain hosting services

 
 

Domain registration : Buy domain name or register domain name from $5.95/year only