官方模塊說明: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。