使用optparse模块解析命令行输入项,python2.7之后不做进一步开发,而是继续开发argparse模块来替代。
from optparse import OptionParser
parser = OptionParser("%prog :HELP info")
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")
执行这个脚本时,能得到清晰的帮助信息:
C:\>Python tst.py -h
Usage: tst.py :HELP info
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 stdout
并且通过(options, args) = parser.parse_args()获得命令行输入的各项,然后就可以针对各项进行处理:
C:\>Python tst.py -f xx.txt 121212
{'verbose': True, 'filename': 'xx.txt'} ['121212']
options 是一个包含选项/值队的dictionary, 而args是一个存储用户传入参数的列表。
Following option attributes may be passed as keyword arguments to OptionParser.add_option().
-
Option.
action
-
(default: "store")
Determines optparse‘s behaviour when this option is seen on the command line; the available options are documentedhere.
-
Option.
type
-
(default: "string")
The argument type expected by this option (e.g., "string" or "int"); the available option types are documentedhere.
-
Option.
dest
-
(default: derived from option strings)
If the option’s action implies writing or modifying a value somewhere, this tellsoptparse where to write it:dest names an attribute of theoptions object that optparse builds as it parses the command line.
-
Option.
default
- The value to use for this option’s destination if the option is not seen on the command line. See also OptionParser.set_defaults().
-
Option.
nargs
-
(default: 1)
How many arguments of type type should be consumed when this option is seen. If > 1,optparse will store a tuple of values todest.
-
Option.
const
- For actions that store a constant value, the constant value to store.
-
Option.
choices
- For options of type "choice", the list of strings the user may choose from.
-
Option.
callback
- For options with action "callback", the callable to call when this option is seen. See section Option Callbacks for detail on the arguments passed to the callable.
-
Option.
callback_args
Option.
callback_kwargs
- Additional positional and keyword arguments to pass to callback after the four standard callback arguments.
-
Option.
help
- Help text to print for this option when listing all available options after the user supplies a help option (such as "--help"). If no help text is supplied, the option will be listed without help text. To hide this option, use the special value optparse.SUPPRESS_HELP.
-
Option.
metavar
-
(default: derived from option strings)
Stand-in for the option argument(s) to use when printing help text. See sectionTutorial for an example.