您的位置:首页 > 编程语言 > Python开发

Python getopt模块函数用法小记

2015-03-24 19:03 519 查看
官方模块说明:https://docs.python.org/2/library/getopt.html#module-getopt

shell中几乎所有的命令输入的时候都可以携带合适的参数来扩展其功能,例如:ls -l,cp -f,mkdir -p,ping -c 10等。

前段时间看到同事写了个添加IP的shell脚本,里面使用了高大上的getopt函数,于是就简单琢磨了下,好记性不如烂笔头,索性就做个笔记总结记录一下,也是好久都不写文字性的东西了,开头都不知道该从何写起了。

Python中getopt模块

说明:该模块是用来在终端执行程序时处理命令行参数时使用的。
函数用法格式:getopt.getopt(args, options[, long_options])
args:命令行参数,一般是sys.argv[1:],0为脚本本身的名字;

options:shortopts 短格式(“-”)
long_options:longopts 长格式(“--”)
命令行示例:
python config.py -h -d 13 -c allow --help

#!/bin/env python
#coding:utf-8
#

import getopt,sys

def usage():
"""
The output  configuration file contents.

Usage: config.py [-d|--domain,[number|'m']] [-c|--cache,[allow|deny]] [-h|--help] [-v|--version] [output, =[argument]]

Description
-d,--domain	Generate domain configuration,take 13 or 19 number,"m" is the second - tier cities.
-c,--cache	Configure cache policy. "allow" or "deny".
-h,--help    Display help information.
-v,--version  Display version number.
for example:
python config.py -d 13
python config.py -c allow
python config.py -h
python config.py -d 13 -c allow
"""

def getopttest():
try:
options,args = getopt.getopt(sys.argv[1:],"d:c:hv",["domain=","cache=","help","version"])
except getopt.GetoptError as err:
print str(err)
print usage.__doc__
sys.exit(1)
for o,a in options:
#for b in args: # Value other than args agruments for getopt format.

if o in ("-d","--domain") and a in ("13"):
ttt.domain(int(a))
elif o in ("-d","--domain") and a in ("19"):
ttt.domain(int(a))
elif o in ("-c","--cache") and a in ("allow"):
ttt.cache("allow")
elif o in ("-h","--help"):
print usage.__doc__
sys.exit()
elif o in ("-v","--version"):
version = xxx
else:
print "Using the wrong way,please view the help information."
if __name__ == "__main__":
getopttest()
代码说明:
注:ttt.domain为我学习时候随便写的一个类方法,测试的话可以修改为print xxx方式。上面代码是我随便写的供测试说明该模块参数作用的示例,不够严谨,有错误的地方大家就自己改改吧。

getopt.GetoptError为getopt模块函数异常错误,这里捕获该异常并打印出相关信息等。
sys.argv[1:]为获取到的命令行参数,赋值给options,options变量在getopt分析完后实际包含两个值,参数和参数值,args值为不属于getopt函数分析内的参数和参数值,例如python config.py -d 13 aaa,则aaa为args变量。

“d:c:hv”: 此为短格式,“:”表示该参数后面需要加参数值,不加冒号使用时则无需添加参数值,例如:-d 13。

["domain=","cache=","help","version"]: 此为长格式,长格式参数后面跟随等号即“=”表示该长格式参数后面需要添加参数值,不加等号则使用时无需添加参数值,例如:--cache allow。

本文出自 “路漫漫修远兮” 博客,请务必保留此出处http://xinghen.blog.51cto.com/1080189/1623926
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: