Whileoptparse is quite flexible and powerful, it's also straightforward touse in most cases. This section covers the code patterns that arecommon to anyoptparse-based program.
First, you need to import the OptionParser class; then, early in themain program, create an OptionParser instance:
from optparse import OptionParser[...]parser = OptionParser()
Then you can start defining options. The basic syntax is:
parser.add_option(opt_str, ..., attr=value, ...)
Each option has one or more option strings, such as-f or--file, and several option attributes that telloptparse what toexpect and what to do when it encounters that option on the commandline.
Typically, each option will have one short option string and one longoption string, e.g.:
parser.add_option("-f", "--file", ...)You're free to define as many short option strings and as many longoption strings as you like (including zero), as long as there is atleast one option string overall.
The option strings passed toadd_option() are effectively labels forthe option defined by that call. For brevity, we will frequently refertoencountering an option on the command line; in reality,optparseencountersoption strings and looks up options from them.
Once all of your options are defined, instructoptparse to parse yourprogram's command line:
(options, args) = parser.parse_args()
(If you like, you can pass a custom argument list toparse_args(),but that's rarely necessary: by default it usessys.argv[1:].)
parse_args() returns two values:
options, an object containing values for all of your options--e.g. if--file takes a single string argument, thenoptions.file will be the filename supplied by the user, orNone if the user did not supply that optionargs, the list of positional arguments leftover after parsingoptionsThis tutorial section only covers the four most important optionattributes:action,type,dest (destination), andhelp.Of these,action is the most fundamental.