Python 基礎文法
Python 提供了
getopt 子產品來擷取指令行參數。$ python test.py arg1 arg2 arg3
Python 中也可以使用
sys的
sys.argv來擷取指令行參數:
- sys.argv 是指令行參數清單。
- len(sys.argv) 是指令行參數個數。
sys.argv[0] 表示腳本名。
執行個體
test.py 檔案代碼如下:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import sys
print '參數個數為:', len(sys.argv), '個參數。'
print '參數清單:', str(sys.argv)
執行以上代碼,輸出結果為:
$ python test.py arg1 arg2 arg3
參數個數為: 4 個參數。
參數清單: ['test.py', 'arg1', 'arg2', 'arg3']
getopt子產品
getopt子產品是專門處理指令行參數的子產品,用于擷取指令行選項和參數,也就是sys.argv。指令行選項使得程式的參數更加靈活。支援短選項模式 - 和長選項模式 --。
該子產品提供了兩個方法及一個異常處理來解析指令行參數。
getopt.getopt 方法
getopt.getopt 方法用于解析指令行參數清單,文法格式如下:
getopt.getopt(args, options[, long_options])
方法參數說明:
- args : 要解析的指令行參數清單。
- options : 以字元串的格式定義, 後的冒号 : 表示如果設定該選項,必須有附加的參數,否則就不附加參數。
- long_options : 以清單的格式定義, 後的等号 = 表示該選項必須有附加的參數,不帶等号表示該選項不附加參數。
- 該方法傳回值由兩個元素組成: 第一個是 (option, value) 元組的清單。 第二個是參數清單,包含那些沒有 - 或 -- 的參數。
另外一個方法是 getopt.gnu_getopt,這裡不多做介紹。
Exception getopt.GetoptError
在沒有找到參數清單,或選項的需要的參數為空時會觸發該異常。
異常的參數是一個字元串,表示錯誤的原因。屬性
msg和
opt為相關選項的錯誤資訊。
假定我們建立這樣一個腳本,可以通過指令行向腳本檔案傳遞兩個檔案名,同時我們通過另外一個選項檢視腳本的使用。腳本使用方法如下:
usage: test.py -i <inputfile> -o <outputfile>
test.py 檔案代碼如下所示:
import sys, getopt
def main(argv):
inputfile = ''
outputfile = ''
try:
opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])
except getopt.GetoptError:
print 'test.py -i <inputfile> -o <outputfile>'
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print 'test.py -i <inputfile> -o <outputfile>'
sys.exit()
elif opt in ("-i", "--ifile"):
inputfile = arg
elif opt in ("-o", "--ofile"):
outputfile = arg
print '輸入的檔案為:', inputfile
print '輸出的檔案為:', outputfile
if __name__ == "__main__":
main(sys.argv[1:])
$ python test.py -h
usage: test.py -i <inputfile> -o <outputfile>
$ python test.py -i inputfile -o outputfile
輸入的檔案為: inputfile
輸出的檔案為: outputfile