問(wèn)題
python腳本如何獲取命令行參數(shù)锨咙,包括選項(xiàng)及非選項(xiàng)參數(shù),例如:
python client.py -b -t timeout host port
python client.py -h
python client.py --help
相關(guān)模塊
python提供了sys模塊獲取參數(shù)侨赡,getopt模塊對(duì)參數(shù)進(jìn)行解析蓖租。
- sys.argv:命令行參數(shù)粱侣,包含腳本名稱本身
- sys.argv[0]:腳本名稱本身羊壹,如client.py
- sys.argv[1:]:命令行參數(shù),不包括腳本名稱
- getopt.getopt():解析命令行參數(shù)
- getopt.gnu_getopt():解析命令行參數(shù)齐婴,選項(xiàng)和非選項(xiàng)可以混合在一起
- getopt.GetoptError:解析命令行參數(shù)時(shí)的異常名稱
- getopt.error:getopt.GetoptError的別稱油猫,向下兼容用
函數(shù)原型及說(shuō)明
getopt和gnu_getopt的原型如下:
getopt(args,options[,long_options])
gnu_getopt(args,options[,long_options])
- args是參數(shù)列表,通常使用sys.argv[1:]柠偶,當(dāng)然也可以自己構(gòu)造一個(gè)參數(shù)列表情妖,如myargv=['-t', '60', '127.0.0.1', '8080']
- options是短參數(shù),如-h诱担,-v毡证,-p 80。
- long_options是長(zhǎng)參數(shù)蔫仙,如--help
函數(shù)調(diào)用說(shuō)明
舉例說(shuō)明料睛,對(duì)于如下調(diào)用:
try:
opts, args = getopt.gnu_getopt(sys.argv[1:], "bht:", ['help','timeout='])
except getopt.GetoptError as e:
print e
sys.exit()
"bht:": 當(dāng)一個(gè)選項(xiàng)只是表示開關(guān)狀態(tài)(不帶附加參數(shù))時(shí),分析串中只寫選項(xiàng)字符。當(dāng)選項(xiàng)帶附加參數(shù)時(shí)恤煞,分析串中寫入選項(xiàng)字符同時(shí)后面加一個(gè)":"號(hào)屎勘。所以"bht:"就表示"b"和"h"是開關(guān)選項(xiàng);"t:"則表示后面帶一個(gè)參數(shù)居扒。
調(diào)用getopt或gnu_getopt函數(shù)時(shí)概漱,函數(shù)返回兩個(gè)列表:opts和args。opts為分析出的格式信息喜喂。args為不屬于格式信息的剩余的命令行參數(shù)瓤摧。opts是一個(gè)兩元組的列表。每個(gè)元素為:(選項(xiàng)串,附加參數(shù))玉吁。如果沒(méi)有附加參數(shù)則為空串''姻灶。
使用長(zhǎng)格式分析串列表:['help','timeout=']。長(zhǎng)格式串也可以有開關(guān)狀態(tài)诈茧,即后面不跟"="號(hào)产喉。如果跟一個(gè)等號(hào)則表示后面還有一個(gè)參數(shù)。這個(gè)例子中敢会,"help"是一個(gè)開關(guān)選項(xiàng)曾沈;"timeout="則表示后面帶一個(gè)參數(shù)。
整個(gè)過(guò)程使用異常來(lái)包含鸥昏,這樣當(dāng)分析出錯(cuò)時(shí)塞俱,就可以打印出用法信息來(lái)通知用戶如何使用這個(gè)程序。
執(zhí)行程序時(shí)吏垮,對(duì)于短格式障涯,"-"號(hào)后面要緊跟一個(gè)選項(xiàng)字母。如果還有此選項(xiàng)的附加參數(shù)膳汪,可以用空格分開唯蝶,也可以不分開。長(zhǎng)度任意遗嗽,也可以用引號(hào)粘我。以下是正確的:
-o
-oa
-obbbb
-o bbbb
-o'ccc'
-o "a b"執(zhí)行程序時(shí),對(duì)于長(zhǎng)格式痹换,"--"號(hào)后面要跟一個(gè)單詞征字。如果選項(xiàng)有附加參數(shù),后面要緊跟"="娇豫,再加上參數(shù)匙姜,"="號(hào)前后不能有空格,或者使用空格分隔選項(xiàng)和附加參數(shù)冯痢,以下是正確的:
--timeout=30
--timeout 30
而這些是不正確的:
-- timeout=30
--timeout =30
--timeout = 30
--timeout= 30
--timeout30getopt和gnu_getopt的區(qū)別在于氮昧,getopt是在非選項(xiàng)參數(shù)之后或详,所有的參數(shù)都被定義為非選項(xiàng)。而gnu_getopt則可以混用郭计,如:client.py -t 30 127.0.0.1 8080 -b霸琴。gnu_getopt是從python 2.3開始引入的。
長(zhǎng)選項(xiàng)會(huì)盡可能長(zhǎng)的識(shí)別昭伸,例如long_options為['foo','frob']梧乘,則--fo會(huì)匹配--foo。但是--f不會(huì)匹配庐杨,而拋出GetoptError異常选调。
實(shí)例
#!/usr/bin/env python
import sys, getopt
timeout = -1
TS = 0
bandwidth = 0
def usage():
print("Usage: %s [OPTION]... [hostname] [port]" % (sys.argv[0]))
print(" -b display bandwidth in bytes")
print(" -h, --help print this help and exit")
print(" -t, --timeout time connection timeout")
print(" --timestamp display timestamp")
print(" -v, --version print version information and exit")
print("sys.argv=|%s|" % sys.argv)
try:
opts, args = getopt.gnu_getopt(sys.argv[1:], "bht:v", ['help','timeout=','version',"timestamp"])
print("opts=|%s|" % opts)
print("args=|%s|" % args)
except getopt.GetoptError as e:
print e
usage()
sys.exit()
for op, value in opts:
if op == "-b":
bandwidth = 1
if op == "-h" or op == "--help":
usage()
sys.exit()
if op in ("-t","--timeout"):
timeout = value
if op == "--timestamp":
TS = 1
if op in ("-v","--version"):
print("%s version: 0.0.1" % sys.argv[0])
sys.exit()
if len(args) != 2:
print("no host or port")
usage()
sys.exit()
host=args[0]
try:
port = int(args[1])
except ValueError as e:
print e
usage()
sys.exit()
print("timeout=%s, host=%s, port=%d, bandwidth=%d, TS=%d" % (timeout, host, port, bandwidth, TS))
驗(yàn)證結(jié)果1
常用的調(diào)用方式
# python client.py -t 30 -b 127.0.0.1 8080
sys.argv=|['client.py', '-t', '30', '-b', '127.0.0.1', '8080']|
opts=|[('-t', '30'), ('-b', '')]|
args=|['127.0.0.1', '8080']|
timeout=30, host=127.0.0.1, port=8080, bandwidth=1, TS=0
驗(yàn)證結(jié)果2
選項(xiàng)和非選項(xiàng)混合的場(chǎng)景
# python client.py -t 30 127.0.0.1 8080 -b
sys.argv=|['client.py', '-t', '30', '127.0.0.1', '8080', '-b']|
opts=|[('-t', '30'), ('-b', '')]|
args=|['127.0.0.1', '8080']|
timeout=30, host=127.0.0.1, port=8080, bandwidth=1, TS=0
驗(yàn)證結(jié)果3
無(wú)附加參數(shù)的短選項(xiàng)合起來(lái)寫,“-b -t”可以寫為“-bt”
# python client.py -bt 30 127.0.0.1 8080
sys.argv=|['client.py', '-bt', '30', '127.0.0.1', '8080']|
opts=|[('-b', ''), ('-t', '30')]|
args=|['127.0.0.1', '8080']|
timeout=30, host=127.0.0.1, port=8080, bandwidth=1, TS=0
[root@test python]#
驗(yàn)證結(jié)果4
短選項(xiàng)與附加參數(shù)合起來(lái)寫
# python client.py -bt30 127.0.0.1 8080
sys.argv=|['client.py', '-bt30', '127.0.0.1', '8080']|
opts=|[('-b', ''), ('-t', '30')]|
args=|['127.0.0.1', '8080']|
timeout=30, host=127.0.0.1, port=8080, bandwidth=1, TS=0
驗(yàn)證結(jié)果5
只有短選項(xiàng)灵份,且沒(méi)有附加參數(shù)
# python client.py -v
sys.argv=|['client.py', '-v']|
opts=|[('-v', '')]|
args=|[]|
client.py version: 0.0.1
驗(yàn)證結(jié)果6
只有長(zhǎng)選項(xiàng)仁堪,且沒(méi)有附加參數(shù)
# python client.py --version
sys.argv=|['client.py', '--version']|
opts=|[('--version', '')]|
args=|[]|
client.py version: 0.0.1
驗(yàn)證結(jié)果7
--ver匹配--version
# python client.py --ver
sys.argv=|['client.py', '--ver']|
opts=|[('--version', '')]|
args=|[]|
client.py version: 0.0.1
驗(yàn)證結(jié)果8
無(wú)法識(shí)別選項(xiàng)的異常
# python client.py -i
sys.argv=|['client.py', '-i']|
option -i not recognized
Usage: client.py [OPTION]... [hostname] [port]
-b display bandwidth in bytes
-h, --help print this help and exit
-t, --timeout time connection timeout
--timestamp display timestamp
-v, --version print version information and exit
驗(yàn)證結(jié)果9
沒(méi)有必要的附加參數(shù)的異常
# python client.py -t
sys.argv=|['client.py', '-t']|
option -t requires argument
Usage: client.py [OPTION]... [hostname] [port]
-b display bandwidth in bytes
-h, --help print this help and exit
-t, --timeout time connection timeout
--timestamp display timestamp
-v, --version print version information and exit
驗(yàn)證結(jié)果10
字符無(wú)法轉(zhuǎn)化成數(shù)字的異常
# python client.py 127.0.0.1 8080abc
sys.argv=|['client.py', '127.0.0.1', '8080abc']|
opts=|[]|
args=|['127.0.0.1', '8080abc']|
invalid literal for int() with base 10: '8080abc'
Usage: client.py [OPTION]... [hostname] [port]
-b display bandwidth in bytes
-h, --help print this help and exit
-t, --timeout time connection timeout
--timestamp display timestamp
-v, --version print version information and exit
驗(yàn)證結(jié)果11
長(zhǎng)選項(xiàng)過(guò)短無(wú)法匹配的異常
# python client.py --time 127.0.0.1 8080
sys.argv=|['client.py', '--time', '127.0.0.1', '8080']|
option --time not a unique prefix
Usage: client.py [OPTION]... [hostname] [port]
-b display bandwidth in bytes
-h, --help print this help and exit
-t, --timeout time connection timeout
--timestamp display timestamp
-v, --version print version information and exit