Python 中的引數解析
每種程式語言都具有建立指令碼並從終端執行或被其他程式呼叫的功能。在執行此類指令碼時,我們通常需要傳遞指令碼執行各種功能所需的引數。在本文中,我們將瞭解將引數傳遞到 Python 指令碼的各種方法。
使用 sys.argv
這是一個內建模組,sys.argv 可以處理與指令碼一起傳遞的引數。預設情況下,在 sys.argv[0] 中考慮的第一個引數是檔名。其餘引數的索引為 1、2 等。在下面的示例中,我們將看到指令碼如何使用傳遞給它的引數。
import sys print(sys.argv[0]) print("Hello ",sys.argv[1],", welcome!")
我們採取以下步驟執行上述指令碼並獲得以下結果
要執行上述程式碼,我們轉到終端視窗並編寫如下所示的命令。這裡指令碼的名稱是 args_demo.py。我們將一個值為 Samantha 的引數傳遞給此指令碼。
D:\Pythons\py3projects>python3 args_demo.py Samantha args_demo.py Hello Samantha welcome!
使用 getopt
這是另一種方法,與前一種方法相比,它具有更大的靈活性。在這裡,我們可以收集引數的值並與錯誤處理和異常一起處理它們。在下面的程式中,我們透過獲取引數並跳過第一個引數(即檔名)來找到兩個數字的乘積。當然,這裡也使用了 sys 模組。
示例
import getopt import sys # Remove the first argument( the filename) all_args = sys.argv[1:] prod = 1 try: # Gather the arguments opts, arg = getopt.getopt(all_args, 'x:y:') # Should have exactly two options if len(opts) != 2: print ('usage: args_demo.py -x <first_value> -b <second_value>') else: # Iterate over the options and values for opt, arg_val in opts: prod *= int(arg_val) print('Product of the two numbers is {}'.format(prod)) except getopt.GetoptError: print ('usage: args_demo.py -a <first_value> -b <second_value>') sys.exit(2)
輸出
執行上述程式碼將得到以下結果:
D:\Pythons\py3projects >python3 args_demo.py -x 3 -y 12 Product of the two numbers is 36 # Next Run D:\Pythons\py3projects >python3 args_demo.py usage: args_demo.py -x <first_value> -b <second_value>
使用 argparse
這實際上是最常用的處理引數傳遞的模組,因為錯誤和異常由模組本身處理,無需額外的程式碼行。我們必須為將要使用的每個引數提及名稱和幫助文字,然後在程式碼的其他部分使用引數的名稱。
示例
import argparse # Construct an argument parser all_args = argparse.ArgumentParser() # Add arguments to the parser all_args.add_argument("-x", "--Value1", required=True, help="first Value") all_args.add_argument("-y", "--Value2", required=True, help="second Value") args = vars(all_args.parse_args()) # Find the product print("Product is {}".format(int(args['Value1']) * int(args['Value2'])))
輸出
執行上述程式碼將得到以下結果:
D:\Pythons\py3projects>python3 args_demo.py -x 3 -y 21 Product is 63 # Next Run D:\Pythons\py3projects>python3 args_demo.py -x 3 -y usage: args_demo.py [-h] -x VALUE1 -y VALUE2 args_demo.py: error: argument -y/--Value2: expected one argument
廣告