Python3 命令行參數


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

$ python test.py arg1 arg2 arg3

Python 中也可以所用 sys 的 sys.argv 來獲取命令行參數:

  • sys.argv 是命令行參數列表。

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

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

實例

test.py 文件代碼如下:

#!/usr/bin/python3

import sys

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

執行以上代碼,輸出結果為:

$ python3 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/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:])

執行以上代碼,輸出結果為:

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

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM