python中getopt函数_Python 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,--domainGenerate domain configuration,take 13 or 19 number,"m" is the second - tier cities.

-c,--cacheConfigure 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。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值