2011-8-23
Python 里边的parser用法
15.5. optparse — Parser for command
line options
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()
With these few lines of code, users of your script can now do the “usual thing” on the command-line, for example:
--file=outfile -q
Thus, the following command lines are all equivalent to the above example:
-f outfile --quiet
--quiet --file outfile
-q -foutfile
-qfoutfile
Additionally, users can run one of
-h
--help
and optparse will print out a brief summary of your script’s options:
Usage: [options]
Options:
-h, --help show this help message and exit
-f FILE, --file=FILE write report to FILE
-q, --quiet don't print status messages to std