1. 程式人生 > >[work] Python 命令列引數

[work] 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 : 以字串的格式定義,options 後的等號 = 表示如果設定該選項,必須有附加的引數,否則就不附加引數。

  • long_options : 以列表的格式定義,long_options 後的冒號 : 表示該選項必須有附加的引數,不帶冒號表示該選項不附加引數。

  • 該方法返回值由兩個元素組成: 第一個是 (option, value) 元組的列表。 第二個是引數列表,包含那些沒有 -

     或 -- 的引數。

另外一個方法是 getopt.gnu_getopt,這裡不多做介紹。


Exception getopt.GetoptError

在沒有找到引數列表,或選項的需要的引數為空時會觸發該異常。

異常的引數是一個字串,表示錯誤的原因。屬性 msg 和 opt 為相關選項的錯誤資訊。

例項

假定我們建立這樣一個指令碼,可以通過命令列向指令碼檔案傳遞兩個檔名,同時我們通過另外一個選項檢視指令碼的使用。指令碼使用方法如下:

usage: test.py -i <inputfile> -o <outputfile>

test.py 檔案程式碼如下所示:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

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