optparse模块
2016-04-30 17:09
253 查看
原文链接:https://www.geek-share.com/detail/2673007340.html
执行结果如下:
optparse模块主要是用来对参数的记录,相对来说比较灵活,
例子代码如下:
#!/usr/bin/env python from optparse import OptionParser usage = 'usage:%prog [options] arg' #主要是总的使用信息,表示如何来使用此方法或者其他 parser = OptionParser(usage) #构造optionparse object parser.add_option('-f','--file',dest='filename', help='write report to FILE',metavar='FILE') #设置的第一个参数 parser.add_option('-q','--quite', action='store_false',dest='verbose',default=True, help="'don't print status messages to stdout") #设置的第二个参数 args = ['kel'] (options,args) = parser.parse_args(args) print options print args执行代码如下:
[root@python 429]# ./optparseexample.py -h Usage: usage:optparseexample.py [options] arg Options: -h, --help show this help message and exit -f FILE, --file=FILE write report to FILE -q, --quite 'don't print status messages to stdout使用 -h的时候,表示为帮助,在使用构造的时候,可以看到传入的参数usage,表示主要的使用方法,而在两个参数均有help,那么也会打印出帮助信息,
在设置参数的时候,可以使用长的,或者短的参数,例如在第一个参数中设置的-f和--file,均表示同一个参数,dest表示设置的属性,也就是设置了参数-f,那么就会有一个参数为options.filename,第二个参数为options.verbose
dest参数表示设置的属性名称,default表示设置的默认值,
action参数表示store_true或者store_false,表示设置布尔值,true或者是false
其他的action参数还有store_const表示一个常量,append,表示追加这个参数到一个列表,count表示计数,callback表示为可以使用的方法
#!/usr/bin/env python from optparse import OptionParser usage = 'this is the method of the script' parser = OptionParser(usage) parser.add_option('-f','--file',dest='filename' ,help='this is the filename') (options,args) = parser.parse_args() print options print args ~
执行结果如下:
[root@python 430]# python optparseexample.py -f kel {'filename': 'kel'} []当引用结果的时候,就是使用options.filename,从而可以引用这个值。
转载于:https://www.cnblogs.com/kellyseeme/p/5525033.html
相关文章推荐
- python笔记12-比sys.argv厉害的optparse模块
- 【转】optparse 模块OptionParser学习记录
- Python模块学习——optparse
- Python模块optparse
- Python模块之optparse
- 内置模块 - optparse
- Python模块整理(七):选项模块Optparse
- python optparse 模块使用
- python optparse命令解析模块
- 【python】optparse 模块
- Python模块学习——optparse
- Python模块学习——optparse
- python optparse命令解析模块
- 【python】optparse 模块
- optparse 模块—— 命令行选项的解析器
- [转]Python模块学习——optparse
- Python中optparse模块使用学习
- optparse 模块—— 命令行选项的解析器
- Python:模块optparse
- Python模块学习——optparse