Python 的 C 風格命令列選項解析器


Python 的 sys 模組透過 sys.argv 提供對任何命令列引數的訪問。sys.argv 是命令列引數的列表,sys.argv[0] 是程式,即指令碼名稱。

將以下程式碼儲存為 args.py

import sys
print ('argument list', sys.argv)

從命令列執行上述指令碼,如下所示

C:\python37>python args.py 11 22
argument list ['args.py', '11', '22']

getopt 模組包含用於解析 sys.argv 中命令列引數的函式。它支援與 Unix getopt() 函式相同的約定(包括對“-”和“--”形式引數的特殊含義)。

API 的設計旨在方便 C getopt() 函式的使用者使用。

getopt(args, shortopts, longopts=[])

解析命令列選項和引數列表。args 是引數列表,不包括 sys.argv[0](這是對正在執行程式的前導引用)。通常,這意味著 sys.argv[1:]。此函式的引數如下:

**shortopts:** 是指令碼將識別的選項字母字串。需要引數的選項後跟一個冒號(':';即 Unix getopt() 使用的相同格式)。

**Longopts:** 如果指定,必須是包含應支援的長選項名稱的字串列表。“--”字元不應包含在選項名稱中。需要引數的長選項後應跟一個等號('=')。

返回值包含兩個元素:第一個是 (選項,值) 對的列表;第二個是從選項列表中剝離後剩餘的程式引數列表(這是 args 的尾隨切片)。返回的每個選項值對都將選項作為其第一個元素,短選項字首為連字元(例如,“-x”),長選項字首為雙連字元(例如,“--long-option”),選項引數作為其第二個元素,或者如果選項沒有引數則為空字串。選項按找到的順序出現在列表中,從而允許多次出現。長選項和短選項可以混合使用。

當在引數列表中找到無法識別的選項或需要引數的選項未提供引數時,將引發 GetoptError。

示例

import sys, getopt

args=sys.argv[1:]
inputfile = ''
outputfile = ''
try:
   opts, args = getopt.getopt(args,"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 ('args.py -i <inputfile> -o <outputfile>')
      sys.exit()
   elif opt in ("-i", "--ifile"):
      inputfile = arg
   elif opt in ("-o", "--ofile"):
      outputfile = arg
print ('Input file is "', inputfile)
print ('Output file is "', outputfile)

輸出

C:\python37>python args.py -h
args.py -i <inputfile> -o <outputfile>
C:\python37>python args.py -i abc.txt -o xyz.txt
Input file is " abc.txt
Output file is " xyz.txt
C:\python37>python args.py --ifile=abc.txt --ofile=xyz.txt
Input file is " abc.txt
Output file is " xyz.txt

更新於:2019年7月30日

276 次瀏覽

啟動您的 職業生涯

完成課程獲得認證

開始
廣告