Python中optparse模块使用浅析

2019-10-05 11:10:56丽君

>>> usage = "myprog[ -f <filename>][-s <xyz>] arg1[,arg2..]"
>>> parser=OptionParser(usage) #这里为类添加了参数usage
>>> optParser.add_option("-f","--file",action = "store",type="string",dest = "fileName",help="no any help")
<Option at 0x2bdb888: -f/--file>
>>> fakeArgs = ['-f','file.txt']
>>> options, args = parser.parse_args(fakeArgs)
>>> options.fileName
'file.txt'
>>> parser.print_help()
Usage: myprog[ -f <filename>][-s <xyz>] arg1[,arg2..]

Options:
  -h, --help            show this help message and exit  #此两行根据option自动生成,比较智能额~~
  -f FILENAME, --file=FILENAME
                        no any help  #这是我定义的帮助信息(呵呵,不太友好~~)
>>> parser.print_usage()
Usage: myprog[ -f <filename>][-s <xyz>] arg1[,arg2..]  #这是类的usage信息~~很逼真,有木有?

>>>


上述是介绍基本的语法,下面举两个例子,一个是网上找的一个模拟命令行的参数的例子,另一个是“真实”的例子~~~

Example1:

from optparse import OptionParser
usage = "myprog[ -f <filename>][-s <xyz>] arg1[,arg2..]"
optParser = OptionParser(usage)
optParser.add_option("-f","--file",action = "store",type="string",dest = "fileName")
ooptParser.add_option("-v","--vison", action="store_false", dest="verbose",default='None',
                     help="make lots of noise [default]")
fakeArgs = ['-f','file.txt','-v','good luck to you', 'arg2', 'arge'] 
options, args = optParser.parse_args(fakeArgs)
print options.fileName
print options.verbose
print options
print args
print optParser.print_help()

运行结果是:


file.txt
False
{'verbose': False, 'fileName': 'file.txt'}
['this is some what', 'arg2', 'arge']
Usage: myprog[ -f <filename>][-s <xyz>] arg1[,arg2..]
Options:
  -h, --help            show this help message and exit
  -f FILENAME, --file=FILENAME
  -v, --vison           make lots of noise [default]

Example2:

一个简单的例子,就是将给脚本传选项n时,则输出的是n的参数的值,否则给出默认值(脚本保存在E盘):


from optparse import OptionParser
optParser = OptionParser()
optParser.add_option("-n","--number",action = "store",type="int",dest = "intNumber")