14.3.3.1 Creating the parser
The first step in using optparse is to create an OptionParser instance:
parser = OptionParser(...)
The OptionParser constructor has no required arguments, but a number of optional keyword arguments. You should always pass them as keyword arguments, i.e. do not rely on the order in which the arguments are declared.
- The usage summary to print when your program is run incorrectly or
with a help option. When optparse prints the usage string, it expands
%progtoos.path.basename(sys.argv[0])(or toprogif you passed that keyword argument). To suppress a usage message, pass the special valueoptparse.SUPPRESS_USAGE. - A list of Option objects to populate the parser with. The options
in
option_listare added after any options instandard_option_list(a class attribute that may be set by OptionParser subclasses), but before any version or help options. Deprecated; use add_option() after creating the parser instead. - Class to use when adding options to the parser in add_option().
- A version string to print when the user supplies a version option.
If you supply a true value for
version, optparse automatically adds a version option with the single option string"-version". The substring"%prog"is expanded the same as forusage. - Specifies what to do when options with conflicting option strings are added to the parser; see section 14.3.3, Conflicts between options.
- A paragraph of text giving a brief overview of your program. optparse
reformats this paragraph to fit the current terminal width and
prints it when the user requests help (after
usage, but before the list of options). - An instance of optparse.HelpFormatter that will be used for printing help text. optparse provides two concrete classes for this purpose: IndentedHelpFormatter and TitledHelpFormatter.
- If true, optparse will add a help option (with option strings
"-h"and"-help") to the parser. - The string to use when expanding
"%prog"inusageandversioninstead ofos.path.basename(sys.argv[0]).
See About this document... for information on suggesting changes.





