getopt()函數(shù)
作用
- 解析獲取到的命令行參數(shù),一般用來(lái)解析sys.argv
使用
- getopt()函數(shù)為getopt模塊內(nèi)置函數(shù)色迂。需導(dǎo)入getopt模塊。
- opts,args = getopt.getopt(args,shortopts,longopts)
- args是要解析的參數(shù)列表。用戶命令行參數(shù)列表一般為sys.argv[1:]。
- shortopts:單個(gè)字符的短參數(shù)女轿,若該參數(shù)后加:箭启,表示該參數(shù)是有值的。
- longopts:多個(gè)字符的長(zhǎng)參數(shù)蛉迹,若該參數(shù)后加=傅寡,表示該參數(shù)是有值的。
- 返回值是一個(gè)元組由兩個(gè)列表組成北救,opts是由分別匹配到的命令行參數(shù)和對(duì)應(yīng)值組成的元組構(gòu)成荐操,args是由沒(méi)有匹配到的值構(gòu)成
- 使用for opt,value in opts 遍歷匹配到的命令行參數(shù)珍策,用if判斷執(zhí)行相應(yīng)功能
例1
1 import sys
2 import getopt
3 opts,args = getopt.getopt(sys.argv[1:],"hl:s:",["test=","mh"])
4 print (opts)
5 print (args)
運(yùn)行演示
m@m-virtual-machine:~$ python3 test.py -h
[('-h', '')]
[]
m@m-virtual-machine:~$ python3 test.py -h a
[('-h', '')]
['a']
m@m-virtual-machine:~$ python3 test.py -h -s a
[('-h', ''), ('-s', 'a')]
[]
m@m-virtual-machine:~$ python3 test.py -h -s a -l b
[('-h', ''), ('-s', 'a'), ('-l', 'b')]
[]
m@m-virtual-machine:~$ python3 test.py -h -s a -l b --test=c
[('-h', ''), ('-s', 'a'), ('-l', 'b'), ('--test', 'c')]
[]
m@m-virtual-machine:~$ python3 test.py -h -s a -l b --test=c --mh
[('-h', ''), ('-s', 'a'), ('-l', 'b'), ('--test', 'c'), ('--mh', '')]
[]
例2
1 import sys
2 import getopt
3 opts,args = getopt.getopt(sys.argv[1:],"a:b:",["help"])
4 print (opts)
5 print (args)
6 for opt,value in opts:
7 if opt == '--help':
8 print("使用說(shuō)明:")
9 print("-a ip -p port")
10 print("--help 獲取使用說(shuō)明")
運(yùn)行演示
m@m-virtual-machine:~$ python3 test.py --help
[('--help', '')]
[]
使用說(shuō)明:
-a ip -p port
--help 獲取使用說(shuō)明