How optparse handles errors

There are two broad classes of errors that optparse has to worry about: programmer errors and user errors. Programmer errors are usually erroneous calls to parser.add_option(), e.g. invalid option strings, unknown option attributes, missing option attributes, etc. These are dealt with in the usual way: raise an exception (either optparse.OptionError or TypeError) and let the program crash.

Handling user errors is much more important, since they are guaranteed to happen no matter how stable your code is. optparse can automatically detect some user errors, such as bad option arguments (passing "-n 4x" where -n takes an integer argument), missing arguments ("-n" at the end of the command line, where -n takes an argument of any type). Also, you can call parser.error() to signal an application-defined error condition:

(options, args) = parser.parse_args()
if options.a and options.b:
    parser.error("options -a and -b are mutually exclusive")

In either case, optparse handles the error the same way: it prints the program's usage message and an error message to standard error and exits with error status 2.

Consider the first example above, where the user passes "4x" to an option that takes an integer:

$ /usr/bin/foo -n 4x
usage: foo [options]

foo: error: option -n: invalid integer value: '4x'

Or, where the user fails to pass a value at all:

$ /usr/bin/foo -n
usage: foo [options]

foo: error: -n option requires an argument

optparse-generated error messages take care always to mention the option involved in the error; be sure to do the same when calling parser.error() from your application code.

If optparse's default error-handling behaviour does not suite your needs, you'll need to subclass OptionParser and override exit() and/or error().

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