python optparse模块学习
之前用过的一个python库,可以实现解析命令行参数实现命令行交互,最近再写自动化sql注入工具需要实现命令行交互的功能,由于好久不写,可多细节方面都想不起来了,又重新温习了一下这个库,在这里记录一下使用方法和一些容易被忽视的细节
使用
首先需要导入optparse模块中的OptionParser类,这个类里面有设置和解析命令行参数的方法,然后创建它的一个实例
from optparse import OptionParser
parser = OptionParser()
调用该类的add_option方法设置命令行参数
parser.add_option("-自定义的参数识别标签","--自定义的参数识别标签",action="store/store_true/store_false",type="string/...",dest="" help="")
该函数里面比较重要的几个参数的用法
首先是第一和第二个参数作为调用时的参数的标签,会被识别
action参数:
action参数告诉optparse当它在命令行中遇到选项时该做什么。action有三种存储方式:store、store_false、store_true。如果不指定action的值,默认的是store,store需要在命令行中,标签后跟上参数,并将该命令行参数的值赋值给dest参数中指定的变量。如果action值为store_true,那么在命令行中,参数的标签后不需要跟参数,如果命令行中使用了该参数标签,那么该命令行参数的dest变量的值会为True,store_flase同样不需要指定参数,不过不同的是,指定为store_false的参数标签,其dest的值在标签设置时会被设为False
type参数
type指定dest参数中设置的变量的存储类型,默认为string
dest参数
里面的值为变量名,当action被设置为store时,该变量用户接受参数标签后的参数值
help参数
设置要显示的参数的帮助信息
设置完命令行参数后需要解析命令行参数,使用该类的parse_args方法
(options, args) = parser.parse_args()
该方法会返回两个对象,options为字典类型,里面存放了dest中设置的变量和其对应的命令行参数值,args为列表类型,里面存放多余的命令行参数,一个参数标签后只能跟一个参数,多余的会被存在args中
在python中使用命令行中的参数,解析完了命令行参数,就可以在python中直接调用了,调用方法
options.dest中设置的变量名
通过这种方式就能取到命令行中的参数值了
实例
为了更深的理解,给出几个实例
实例1.action的值为store默认值:
>>> from optparse import OptionParser
>>> parser=OptionParser()
>>> parser.add_option("-u","--url",action="store",type="string",dest="url",help="-u/--url url")
<Option at 0x268ce88: -u/--url>
>>> args=["-h"]
>>> (options,args)=parser.parse_args(args)
Usage: [options]
Options:
-h, --help show this help message and exit
-u URL, --url=URL -u/--url url
>>> args=["-u","inputurl1","inputurl2","inputurl2"]
>>> (options,args)=parser.parse_args(args)
>>> print "%s,%s"%(options,args)
{'url': 'inputurl1'},['inputurl2', 'inputurl2']
>>> print options.url
>>> inputurl1
>>> args=["--url","inputurl1","inputurl2","inputurl2"]
>>> (options,args)=parser.parse_args(args)
>>> print "%s,%s"%(options,args)
{'url': 'inputurl1'},['inputurl2', 'inputurl2']
>>> args=[]
>>> (options,args)=parser.parse_args(args)
>>> print "%s,%s"%(options,args)
{'url': None},[]
>>>
实例2.action的值为store_true
>>> from optparse import OptionParser
>>> parser=OptionParser()
>>> parser.add_option("--dbs",action="store_true",dest="dbs",help="--dbs")
<Option at 0x2316048: --dbs>
>>> args=["--dbs"]
>>> (options,args)=parser.parse_args(args)
>>> print "%s,%s"%(options,args)
{'dbs': True},[]
>>> print options.dbs
True
>>> args=[]
>>> (options,args)=parser.parse_args(args)
>>> print "%s,%s"%(options,args)
{'dbs': None},[]
>>> print options.dbs
None
>>> args=["-h"]
>>> (options,args)=parser.parse_args(args)
Usage: [options]
Options:
-h, --help show this help message and exit
--dbs --dbs
G:\代码>