optparse — 命令行选项剖析器

源代码: Lib/optparse.py

从 3.2 版起弃用: The optparse module is soft deprecated and will not be developed further; development will continue with the argparse 模块。


optparse is a more convenient, flexible, and powerful library for parsing command-line options than the old getopt 模块。 optparse uses a more declarative style of command-line parsing: you create an instance of OptionParser , populate it with options, and parse the command line. optparse allows users to specify options in the conventional GNU/POSIX syntax, and additionally generates usage and help messages for you.

Here’s an example of using optparse in a simple script:

from optparse import OptionParser
...
parser = OptionParser()
parser.add_option("-f", "--file", dest="filename",
                  help="write report to FILE", metavar="FILE")
parser.add_option("-q", "--quiet",
                  action="store_false", dest="verbose", default=True,
                  help="don't print status messages to stdout")
(options, args) = parser.parse_args()