optparse是python非常常用的一个内建模块,用于处理命令参数.
#!/usr/bin/python3
# -*- coding: UTF-8-*-
from optparse import OptionParser
import mytest
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="dont print status messages to stdout")
parser.add_option("-e", "--ee", dest="filename",
default=True, help="helllow world jack and rose", metavar="FI34LE")
(options, args) = parser.parse_args()
print(options)
print(args)
生成的使用和帮助信息:
helo ja
Usage: option.py [options]
Options:
-h, --help show this help message and exit
-f FILE, --file=FILE write report to FILE
-q, --quiet dont print status messages to stdout
-e FI34LE, --ee=FI34LE
helllow world jack and rose
执行命令的形式,如下都是等效的:
%prog -q--file=filename
%prog -q --filefilename
命令行参数选项操作:
-
action:指定Optionparser解析到一个命令行参数时该如何处理.action有一组固定值可选.
-
store:默认,表示将命令行参数值保存在options对象里.
-
store_false/stroe_true:布尔选项,用于处理命令行选项后面不带值的情况,例如上面的–quite.
-
store_false:命令行如果出现了对应的选项,例如-q,则赋值False.
-
store_true:命令行如果出现了对应的选项,则赋值True.
-
store_const:存储恒定值
-
callback:调用指定的函数
-
count:将计数器递增1
-
append:将此选项的参数附加到列表
-
type:参数类型,默认”string”,例如”int”,“float”
-
dest:选项参数在程序中被调用的名称.例如options.verbose
-
default:用于设定参数的默认值.也可以单独用parser.set_default方法来定义.
例如:parser.set_default(filename=”1.txt”)
help:打印出来的help信息,对选项参数的意义解释
- metavar:被称为元变量,他代表用户期望提供给选项的参数.只是影响help信息.metavar参数中的字符串自动显示成大写.