使用 Python 解析命令列引數

Vaibhav Vaibhav 2022年5月17日
使用 Python 解析命令列引數

在從命令列或 shell 執行 Python 程式時,我們可以將值以字串的形式、技術上、引數或選項傳遞給程式。程式可以訪問這些值並執行它,甚至使用這些值進行計算。

本文將討論我們如何使用 Python 解析這些命令列引數並使用它們。

使用 optparse 模組解析命令列引數

optparse 模組是一個靈活方便的 Python 包,用於解析命令列選項。它內建於標準 Python 中。它使用宣告式方法來解析命令列選項。要使用這個包,我們首先必須建立一個 OptionParser 類的物件,然後在 add_option() 方法的幫助下新增有關可能選項或引數的詳細資訊。add_option() 方法接受諸如 option(選項名稱)、type(選項的資料型別)、help(選項的幫助文字)和 default(選項名稱)等引數。選項的預設值(如果未在命令中指定)。要以字典的形式從命令列命令獲取選項及其值,我們可以使用 parse_args() 方法。

讓我們通過一個例子更好地理解這個庫的使用。我們將實現一個簡單的 Python 程式,該程式將檢查三個選項:-a-b-c。這裡,-a-b 代表運算元,+ 是運算子,而 -c 本質上是目標和。此外,程式碼將檢查這些值,如果在命令列命令中找不到值,則為它們分配 0 值,最後,檢查 a + b 是否等於 c。此外,它還將以格式良好的字串列印結果。

import optparse

parser = optparse.OptionParser()
parser.add_option("-a", help="First Number", default=0)
parser.add_option("-b", help="Second Number", default=0)
parser.add_option("-c", help="Sum", default=0)
options, args = parser.parse_args()
a = int(options.a)
b = int(options.b)
c = int(options.c)
s = a + b
print(f"{a} + {b} = {s} and {s} {'==' if s == c else '!='} {c}")

下面簡單解釋一下上面的程式碼。首先,它建立一個 OptionParser() 類物件並新增有關三個目標選項的資訊; -a-b-c。然後它遍歷命令列或 shell 命令來檢查所需的選項。最後,它將所有值儲存在單獨的變數中,計算總和或 a + b,並將其與目標總和或 c 進行比較。

讓我們針對以下命令測試該程式。

python main.py -a 1 -b 2 -c 3
python main.py -a 1
python main.py -b 2
python main.py -c 3
python main.py 1 2 3
python main.py -a 1 2 3
python main.py 1 -b 2 3
python main.py 1 2 -c 3
python main.py 0 0 0
python main.py

輸出:

1 + 2 = 3 and 3 == 3
1 + 0 = 1 and 1 != 0
0 + 2 = 2 and 2 != 0
0 + 0 = 0 and 0 != 3
0 + 0 = 0 and 0 == 0
1 + 0 = 1 and 1 != 0
0 + 2 = 2 and 2 != 0
0 + 0 = 0 and 0 != 3
0 + 0 = 0 and 0 == 0
0 + 0 = 0 and 0 == 0

從輸出中,我們可以推斷當沒有向命令列或 shell 命令提供關鍵字選項或引數時,會考慮預設值。請參閱除第一個之外的測試命令(python main.py -a 1 -b 2 -c 3)以獲得更好的分析。

作者: Vaibhav Vaibhav
Vaibhav Vaibhav avatar Vaibhav Vaibhav avatar

Vaibhav is an artificial intelligence and cloud computing stan. He likes to build end-to-end full-stack web and mobile applications. Besides computer science and technology, he loves playing cricket and badminton, going on bike rides, and doodling.