There are two broad classes of errors thatoptparse has to worry about:programmer errors and user errors. Programmer errors are usuallyerroneous calls toparser.add_option(), e.g. invalid option strings,unknown option attributes, missing option attributes, etc. These aredealt with in the usual way: raise an exception (eitheroptparse.OptionError orTypeError) and let the program crash.
Handling user errors is much more important, since they are guaranteedto happen no matter how stable your code is.optparse can automaticallydetect some user errors, such as bad option arguments (passing"-n4x" where-n takes an integer argument), missing arguments("-n" at the end of the command line, where-n takes an argumentof any type). Also, you can callparser.error() to signal anapplication-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 theprogram's usage message and an error message to standard error andexits with error status 2.
Consider the first example above, where the user passes"4x" to anoption that takes an integer:
$ /usr/bin/foo -n 4xusage: foo [options]foo: error: option -n: invalid integer value: '4x'
Or, where the user fails to pass a value at all:
$ /usr/bin/foo -nusage: foo [options]foo: error: -n option requires an argument
optparse-generated error messages take care always to mention the optioninvolved in the error; be sure to do the same when callingparser.error() from your application code.
Ifoptparse's default error-handling behaviour does not suite your needs,you'll need to subclass OptionParser and overrideexit() and/orerror().