Python3 命令行參數(shù)

Python 提供了 getopt 模塊來獲取命令行參數(shù)。

$ python test.py arg1 arg2 arg3

Python 中也可以所用 syssys.argv 來獲取命令行參數(shù):

  • sys.argv 是命令行參數(shù)列表。

  • len(sys.argv) 是命令行參數(shù)個數(shù)。

注:sys.argv[0] 表示腳本名。

實例

test.py 文件代碼如下:

#!/usr/bin/python3

import sys

print ('參數(shù)個數(shù)為:', len(sys.argv), '個參數(shù)。')
print ('參數(shù)列表:', str(sys.argv))

執(zhí)行以上代碼,輸出結(jié)果為:

$ python3 test.py arg1 arg2 arg3
參數(shù)個數(shù)為: 4 個參數(shù)。
參數(shù)列表: ['test.py', 'arg1', 'arg2', 'arg3']

getopt模塊

getopt模塊是專門處理命令行參數(shù)的模塊,用于獲取命令行選項和參數(shù),也就是sys.argv。命令行選項使得程序的參數(shù)更加靈活。支持短選項模式(-)和長選項模式(--)。

該模塊提供了兩個方法及一個異常處理來解析命令行參數(shù)。

getopt.getopt 方法

getopt.getopt 方法用于解析命令行參數(shù)列表,語法格式如下:

getopt.getopt(args, options[, long_options])

方法參數(shù)說明:

  • args: 要解析的命令行參數(shù)列表。

  • options: 以字符串的格式定義,options后的冒號(:)表示該選項必須有附加的參數(shù),不帶冒號表示該選項不附加參數(shù)。

  • long_options: 以列表的格式定義,long_options 后的等號(=)表示如果設(shè)置該選項,必須有附加的參數(shù),否則就不附加參數(shù)。

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

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


Exception getopt.GetoptError

在沒有找到參數(shù)列表,或選項的需要的參數(shù)為空時會觸發(fā)該異常。

異常的參數(shù)是一個字符串,表示錯誤的原因。屬性 msgopt 為相關(guān)選項的錯誤信息。

實例

假定我們創(chuàng)建這樣一個腳本,可以通過命令行向腳本文件傳遞兩個文件名,同時我們通過另外一個選項查看腳本的使用。腳本使用方法如下:

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

test.py 文件代碼如下所示:

#!/usr/bin/python3

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:])

執(zhí)行以上代碼,輸出結(jié)果為:

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

$ python3 test.py -i inputfile -o outputfile
輸入的文件為: inputfile
輸出的文件為: outputfile