1、简介
- python中有两个内建模块用于处理命令行参数:
getopt,只能简单的处理命令行参数;
optparse,功能强大,易于使用,可以很方便的生成标准的,符合Unix/Posix规范的命令行说明。
2、使用流程
a. 必须有import OptionParser类,创建一个OptionParser对象
parser = OptionParser()
b. 使用 add_option 来定义命令行参数
parser.add_option(opt_str, ...,
attr=value, ...)
//每个命令行参数就是由参数名字符串和参数属性组成的。如 -f 或者 –file 分别是长短参数名
c. 定义好了所有的命令行参数,调用 parse_args() 来解析程序的命令行
(options, args) = parser.parse_args()
parse_args() 返回的两个值:
* options,它是一个对象(optpars.Values),保存有命令行参数值。只要知道命令行参数名,如 file,就可以访问其对应的值: options.file 。
* args,它是一个由 positional arguments 组成的列表。
d. 参数
action 它指示 optparse 当解析到一个命令行参数时该如何处理。默认是’store ‘,表示将命令行参数值保存在 options 对象里。
type 默认地,type 为’string’.
dest 参数也是可选的。如果没有指定 dest 参数,将用命令行的参数名来对 options 对象的值进行存取。
store 也有其它的两种形式: store_true 和 store_false ,用于处理带命令行参数后面不 带值的情况。
e. 生成程序帮助
- optparse 另一个方便的功能是自动生成程序的帮助信息。你只需要为 add_option() 方法的 help 参数指定帮助信息文本:
usage = "usage: %prog [options] arg1 arg2"
parser = OptionParser(usage=usage)
parser.add_option("-v", "--verbose",
action="store_true", dest="verbose", default=True,
help="make lots of noise [default]")
parser.add_option("-q", "--quiet",
action="store_false", dest="verbose",
help="be vewwy quiet (I'm hunting wabbits)")
parser.add_option("-f", "--filename",
metavar="FILE", help="write output to FILE"),
parser.add_option("-m", "--mode",
default="intermediate",
help="interaction mode: novice, intermediate, "
"or expert [default: %default]")
- 当 optparse 解析到 -h 或者 –help 命令行参数时,会调用 parser.print_help() 打印程序的帮助信息:
usage: <yourscript> [options] arg1 arg2
options:
-h, --help show this help message and exit
-v, --verbose make lots of noise [default]
-q, --quiet be vewwy quiet (I'm hunting wabbits)
-f FILE, --filename=FILE
write output to FILE
-m MODE, --mode=MODE interaction mode: novice, intermediate, or
expert [default: intermediate]