Python optionParser模块
from http://www.hi-roy.com/2013/11/11/python-optionParser%E6%A8%A1%E5%9D%97/
用于生成模块说明。
#coding=utf-8 from optparse import OptionParser def opt(): parser = OptionParser( description="整个文件功能一类的帮助信息") parser.add_option("-x", "--xxx", dest="xxx", action="store", help="单个参数的帮助信息", metavar="希望接受值的示例")#metavar用于提示希望接受的值示例 parser.add_option("-n", "--num", dest="num", action="store",type="int",metavar="number", #type指明了类型,默认为string help="单个参数的帮助信息,有默认值,整型", default=1) #如果参数中没明确给出值,则设为default的值 parser.add_option("-t", "--settrue", dest="testbool", action="store_true",#这个类型的添加metavar无效,用于判断是否出现了某个参数,如果出现了为ture help="Test bool") parser.add_option("-f", "--setfalse", dest="testbool", action="store_false",#这个类型的添加metavar无效,用于判断是否出现了某个参数,如果出现了为false help="Test bool", default=False) #如果都出现以最后的出现为准,如果都没出现以有default的为准 (options, args) = parser.parse_args() return options if __name__ == '__main__': m = opt() print m.xxx print m.num print type(m.num) print m.testbool
参数为-h时候输出:
Usage: options.py [options] 整个文件功能一类的帮助信息 Options: -h, --help show this help message and exit -x 希望接受值的示例, --xxx=希望接受值的示例 单个参数的帮助信息 -n number, --num=number 单个参数的帮助信息,有默认值,整型 -t, --settrue Test bool -f, --setfalse Test bool
参数是-x test -n 5 -f 时候输出
test 5 <type 'int'> False
小小菜鸟一枚
浙公网安备 33010602011771号