解析parse之Python optionParse模块使用方法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xiaomifanhxx/article/details/83143297

optparse是一个能够让程序设计人员轻松设计出简单明了、易于使用、符合标准的unix命令例程式的Python模块。生成使用和帮助信息。

1  首先导入该类,并且创建OptionParser对象

from optparse import OptionParser
parser=OptionParser()##创建OptionParser对象

2  然后对parser使用add_option()函数添加对命令行解析

add_option参数:action:

action的取值很多,着重说三个store、store_false、store_true 三个取值。 action默认取值store。

       --store 上表示命令行参数的值保存在options对象中。例如上面一段代码,如果我们对optParser.parse_args()函数传入的参数列表中带有‘-f’,那么就会将列表中‘-f’的下一个元素作为其dest的实参filename的值,他们两个参数形成一个字典中的一个元素{filename:file_txt}。相反当我们的参数列表中没有‘-f’这个元素时,那么filename的值就会为空。

      --store_false fakeArgs 中存在'-v'verbose将会返回False,而不是‘how are you’,也就是说verbose的值与'-v'的后一位无关,只与‘-v’存在不存在有关。

      --store_ture  这与action="store_false"类似,只有其中有参数'-v'存在,则verbose的值为True,如果'-v'不存在,那么verbose的值为None。 type, dest,default,help;

-h是把help信息输出出来

from optparse import OptionParser
parser=OptionParser()
parser.add_option('-f','--file',action='store',type='string',dest='filename',default='123.txt',help='dalss')
parser.add_option('-w','--weights',action='store',type='string',dest='weights_path',default='123.h5',help='dals')
dict=['-f','1245.txt']
options,arg=parser.parse_args(dict)
print('options:',options)
print('arg:',arg)

输入没有'-h'的输出如上图所示

输入有‘-h’的输出如下图所示

3当对所有命令行参数都定义好后,使用parse_args()函数来进行解析参数

options,args=parser.parser.args()

options是一个字典,key是add_option()函数中对应的‘dest’参数值,其对应的value值是命令行输入的对应add_option()函数的参数值。

猜你喜欢

转载自blog.csdn.net/xiaomifanhxx/article/details/83143297