The optparse Module

The optparse module offers rich, powerful ways to parse the command-line options (a.k.a. flags) that the user passed upon starting your programs (by using syntax elements such as –x or --foo=bar on the command line, after your program name and before other program arguments). Instantiate (without arguments) the OptionParser class supplied by the module, populate the instance so it knows about your program’s options (by calls to its add_option method), and finally call the instance’s parse_args method to handle your program’s command line, dealing with each option appropriately and returning the collection of option values and a list of nonoption arguments.

optparse supports many advanced ways to customize and fine-tune your program’s option-parsing behavior. In most cases, you can accept optparse’s reasonable defaults and use it effectively with just the two methods of class OptionParser that I cover here (omitting many advanced options of these methods, which you do not normally need). For all of the powerful and complex details, consult Python’s online docs.

An OptionParser instance p supplies the following methods.

add_option

p.add_option(opt_str,*opt_strs,**kw)

The positional arguments specify the option strings, i.e., the strings that the user passes as part of your program’s command line to set this option. Each argument can be a short-form option string (a string starting with a single dash [hyphen] followed by a single letter or digit) or a long-form option ...

Get Python in a Nutshell, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.