【python中模块是什么】python中模块optparse获取参数详解

更新时间:2019-10-28    来源:python    手机版     字体:

【www.bbyears.com--python】

python作为我们干运维的重要的语言,肯定我们大家都写了不少,我们写东西不是为了给我们自己用,而是我们团队或者更多人用。

那么就不得不说下python下获取参数的方法啦。python自带的模块optparse就是我们一直喜欢和常用的啦(当然也有getopt,但是没这个好用)。废话不说了,下面说说怎么用吧!!

首先贴一下官方文档地址:http://docs.python.org/2/library/optparse.html

讲之前先引用下默认字体自带的例子:


from optparse import OptionParser
    
parser = OptionParser()
parser.add_option("-f", "--file", dest="filename",
                         help="write report to FILE", metavar="FILE")
parser.add_option("-q", "--quiet",
                         action="store_false", dest="verbose", default=True,
                         help="don"t print status messages to stdout")
    
(options, args) = parser.parse_args()
这里引入了两个参数,分别是: -f 和 -q 。 可以看到通过add_option函数添加选项。-f参数中,add_option函数参数上面依次是短选项,长选项,描述信息,帮助信息,默认变量名。
下面的-q参数,是用来表示后面不需要跟参数的情况。add_option函数参数上面依次是短选项,长选项,存储动作(默认是store、还有store_false和store_true),,默认值,帮助信息。

在action中:store_ture/store_false保存相应的布尔值。这两个动作被用于实现布尔开关。

除了上面出现的参数,还有type(表示参数的数据类型:有string,int等)。

我们还可以把参数进行分组,使用方法optparse.OptionGroup。


group = OptionGroup(parser, "title", "description")
group.add_option("-g", action="store_true", help="Group option.")
parser.add_option_group(group)
然后还有version,usage, description的用法,完整的见下面截图:

好了,贴一下运行结果:


root@AN-BT5:/apps/python# python test.py -h
Usage: test.py [options] arg1 arg2
 
this is a test script!!!
 
Options:
  --version             show program"s version number and exit
  -h, --help            show this help message and exit
  -f FILE, --file=FILE  write report to FILE
  -n NUMBER, --num=NUMBER
                        define number
  -q, --quiet           don"t print status messages to stdout
 
  title:
    description
 
    -g                  Group option.
root@AN-BT5:/apps/python# python test.py -n 1
{"number": 1, "verbose": True, "g": None, "filename": None}
[]
root@AN-BT5:/apps/python# python test.py -n 1 -f test.txt
{"number": 1, "verbose": True, "g": None, "filename": "test.txt"}
[]
root@AN-BT5:/apps/python# python test.py -n 1 -f test.txt -g
{"number": 1, "verbose": True, "g": True, "filename": "test.txt"}
[]
root@AN-BT5:/apps/python# python test.py -n 1 -f test.txt -g 1
{"number": 1, "verbose": True, "g": True, "filename": "test.txt"}
["1"]
root@AN-BT5:/apps/python# python test.py -n 1 -f test.txt -g
{"number": 1, "verbose": True, "g": True, "filename": "test.txt"}
[]
root@AN-BT5:/apps/python#
还有个函数print_help我们也经常用到,在校验的时候输出help信息。好了,最后在你脚本里面试试吧

本文来源:http://www.bbyears.com/jiaocheng/75864.html