# 6.20 `optparse` -- Powerful parser for command line options.

New in version 2.3.

The `optparse` module is a powerful, flexible, extensible, easy-to-use command-line parsing library for Python. Using `optparse`, you can add intelligent, sophisticated handling of command-line options to your scripts with very little overhead.

Here's an example of using `optparse` to add some command-line options to a simple script:

    from optparse import OptionParser

    parser = OptionParser()
    parser.add_option("-f", "--file", dest="filename",
                      help="write report to FILE", metavar="FILE")
    parser.add_option("-q", "--quiet",
                      action="store_false", dest="verbose", default=True,
                      help="don't print status messages to stdout")

    (options, args) = parser.parse_args()

With these few lines of code, users of your script can now do the ``usual thing'' on the command-line:

    $ <yourscript> -f outfile --quiet
    $ <yourscript> -qfoutfile
    $ <yourscript> --file=outfile -q
    $ <yourscript> --quiet --file outfile

(All of these result in `options.filename == "outfile"` and `options.verbose == False`, just as you might expect.)

Even niftier, users can run one of

    $ <yourscript> -h
    $ <yourscript> --help

and `optparse` will print out a brief summary of your script's options:

    usage: <yourscript> [options]

    options:
      -h, --help           show this help message and exit
      -fFILE, --file=FILE  write report to FILE
      -q, --quiet          don't print status messages to stdout

That's just a taste of the flexibility `optparse` gives you in parsing your command-line.

Subsections

- 6.20.1 Philosophy
  - 6.20.1.1 Terminology
  - 6.20.1.2 What are options for?
  - 6.20.1.3 What are positional arguments for?
- 6.20.2 Basic Usage
  - 6.20.2.1 The store action
  - 6.20.2.2 Other store_* actions
  - 6.20.2.3 Setting default values
  - 6.20.2.4 Generating help
  - 6.20.2.5 Print a version number
  - 6.20.2.6 Error-handling
  - 6.20.2.7 Putting it all together
- 6.20.3 Advanced Usage
  - 6.20.3.1 Creating and populating the parser
  - 6.20.3.2 Defining options
  - 6.20.3.3 Option actions
  - 6.20.3.4 Option types
  - 6.20.3.5 Querying and manipulating your option parser
  - 6.20.3.6 Conflicts between options
- 6.20.4 Callback Options
  - 6.20.4.1 Defining a callback option
  - 6.20.4.2 How callbacks are called
  - 6.20.4.3 Error handling
  - 6.20.4.4 Examples
- 6.20.5 Extending `optparse`
  - 6.20.5.1 Adding new types
  - 6.20.5.2 Adding new actions
  - 6.20.5.3 Other reasons to extend `optparse`
  - 6.20.5.4 Examples