6.20.2 Basic Usage

While optparse is quite flexible and powerful, you don't have to jump through hoops or read reams of documentation to get it working in basic cases. This document aims to demonstrate some simple usage patterns that will get you started using optparse in your scripts.

To parse a command line with optparse, you must create an OptionParser instance and populate it. Obviously, you'll have to import the OptionParser classes in any script that uses optparse:

from optparse import OptionParser

Early on in the main program, create a parser:

parser = OptionParser()

Then you can start populating the parser with options. Each option is really a set of synonymous option strings; most commonly, you'll have one short option string and one long option string -- e.g. -f and --file:

parser.add_option("-f", "--file", ...)

The interesting stuff, of course, is what comes after the option strings. For now, we'll only cover four of the things you can put there: action, type, dest (destination), and help.

See About this document... for information on suggesting changes.