Python optparse


Python optparse


optparse的作用

optparse模块主要用来为脚本传递命令参数,采用预先定义好的选项来解析命令行参数

如何使用

只需引入optparse模块即可,执行初始化,实例化一个OptionParser对象,在为命令添加选项

使用举例

from optparse import OptionParser
usage="show something usefull
-- for example: how to use this program"
parser = OptionParser(usage) #带参的话会把参数变量的内容作为帮助信息输出
parser.add_option("-f","--file",dest="filename",help="read picture from File",metavar="FILE",action = "store",type="string")
parser.add_option("-s","--save",dest="save_mold",help="save image to file or not",default = True)
(options,args)=parser.parse_args()
print options.filename
print options.save_mold

参数解释

dest

用于保存输入的临时变量,其值通过options的属性进行访问

help

用于生成帮助信息

defalut

给dest的默认值,如果不写,使用默认值

type

用于检查命令行参数传入的参数的数据类型是否复合要求

action

用于知道程序在遇到命令行参数时该如何处理,有三种选择

store (默认)

读取参数,如果复合type的要求,将参数值传递给dest变量,作为options的一个属性供使用

store_false
store_ture

一般作为一个标记使用,分别设置dest变量的值为true会哦false

metavar

占位字符串,用于在输出信息时,代替当前命令选项饿附和参数的值进行输出,只在帮助信息里有用

注: python中optparse模块用法