O'Reilly logo

Python in a Nutshell, 2nd Edition by Alex Martelli

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required