1. 程式人生 > >Python命令行參數

Python命令行參數

ron tool .py -h NPU bar put 參數變量 toolbar

Python提供了一個getopt模塊,用於解析命令行選項和參數。

$ python test.py arg1 arg2 arg3
Shell

Python sys模塊通過sys.argv提供對任何命令行參數的訪問。主要有兩個參數變量 -

  • sys.argv是命令行參數的列表。
  • len(sys.argv)是命令行參數的數量。

這裏sys.argv [0]是程序名稱,即腳本的名稱。比如在上面示例代碼中,sys.argv [0]的值就是 test.py

示例

看看以下腳本command_line_arguments.py的代碼 -

#!/usr/bin/python3
import sys print (Number of arguments:, len(sys.argv), arguments.) print (Argument List:, str(sys.argv))

現在運行上面的腳本,這將產生以下結果 -

F:\>python F:\worksp\python\command_line_arguments.py
Number of arguments: 1 arguments.
Argument List: [F:\\worksp\\python\\command_line_arguments.py
] F:\>python F:\worksp\python\command_line_arguments.py arg1 arg2 arg3 arg4 Number of arguments: 5 arguments. Argument List: [F:\\worksp\\python\\command_line_arguments.py, arg1, arg2, arg3, arg4] F:\>

註意 - 如上所述,第一個參數始終是腳本名稱,它也被計入參數的數量。

解析命令行參數

Python提供了一個getopt模塊,可用於解析命令行選項和參數。該模塊提供了兩個功能和異常,以啟用命令行參數解析。

getopt.getopt方法

此方法解析命令行選項和參數列表。以下是此方法的簡單語法 -

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

getopt.GetoptError異常

當在參數列表中有一個無法識別的選項,或者當需要一個參數的選項不為任何參數時,會引發這個異常。
異常的參數是一個字符串,指示錯誤的原因。 屬性msgopt給出錯誤消息和相關選項。

示例

假設想通過命令行傳遞兩個文件名,也想給出一個選項用來顯示腳本的用法。腳本的用法如下 -

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

以下是command_line_usage.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 (GetoptError, usage: command_line_usage.py -i <inputfile> -o <outputfile>)
      sys.exit(2)
   for opt, arg in opts:
      if opt == -h:
         print (usage: command_line_usage.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)

if __name__ == "__main__":
   main(sys.argv[1:])

現在,使用以下幾種方式運行來腳本,輸出如下所示:

F:\worksp\python>python command_line_usage.py -h
usage: command_line_usage.py -i <inputfile> -o <outputfile>

F:\worksp\python>python command_line_usage.py -i inputfile.txt -o
GetoptError, usage: command_line_usage.py -i <inputfile> -o <outputfile>

F:\worksp\python>python command_line_usage.py -i inputfile.txt -o outputfile.txt
Input file is " inputfile.txt
Output file is " outputfile.txt

F:\worksp\python>

Python命令行參數