
- Python 基礎
- Python - 首頁
- Python - 概述
- Python - 歷史
- Python - 特性
- Python vs C++
- Python - Hello World 程式
- Python - 應用領域
- Python - 直譯器
- Python - 環境設定
- Python - 虛擬環境
- Python - 基本語法
- Python - 變數
- Python - 資料型別
- Python - 型別轉換
- Python - Unicode 系統
- Python - 字面量
- Python - 運算子
- Python - 算術運算子
- Python - 比較運算子
- Python - 賦值運算子
- Python - 邏輯運算子
- Python - 位運算子
- Python - 成員運算子
- Python - 身份運算子
- Python - 運算子優先順序
- Python - 註釋
- Python - 使用者輸入
- Python - 數字
- Python - 布林值
- Python 控制語句
- Python - 控制流
- Python - 決策
- Python - If 語句
- Python - If else
- Python - 巢狀 If
- Python - Match-Case 語句
- Python - 迴圈
- Python - for 迴圈
- Python - for-else 迴圈
- Python - While 迴圈
- Python - break 語句
- Python - continue 語句
- Python - pass 語句
- Python - 巢狀迴圈
- Python 函式 & 模組
- Python - 函式
- Python - 預設引數
- Python - 關鍵字引數
- Python - 僅關鍵字引數
- Python - 位置引數
- Python - 僅位置引數
- Python - 可變引數
- Python - 變數作用域
- Python - 函式註解
- Python - 模組
- Python - 內建函式
- Python 字串
- Python - 字串
- Python - 字串切片
- Python - 修改字串
- Python - 字串連線
- Python - 字串格式化
- Python - 跳脫字元
- Python - 字串方法
- Python - 字串練習
- Python 列表
- Python - 列表
- Python - 訪問列表元素
- Python - 修改列表元素
- Python - 新增列表元素
- Python - 刪除列表元素
- Python - 迴圈遍歷列表
- Python - 列表推導式
- Python - 排序列表
- Python - 複製列表
- Python - 合併列表
- Python - 列表方法
- Python - 列表練習
- Python 元組
- Python - 元組
- Python - 訪問元組元素
- Python - 更新元組
- Python - 解包元組
- Python - 迴圈遍歷元組
- Python - 合併元組
- Python - 元組方法
- Python - 元組練習
- Python 集合
- Python - 集合
- Python - 訪問集合元素
- Python - 新增集合元素
- Python - 刪除集合元素
- Python - 迴圈遍歷集合
- Python - 合併集合
- Python - 複製集合
- Python - 集合運算子
- Python - 集合方法
- Python - 集合練習
- Python 字典
- Python - 字典
- Python - 訪問字典元素
- Python - 修改字典元素
- Python - 新增字典元素
- Python - 刪除字典元素
- Python - 字典檢視物件
- Python - 迴圈遍歷字典
- Python - 複製字典
- Python - 巢狀字典
- Python - 字典方法
- Python - 字典練習
- Python 陣列
- Python - 陣列
- Python - 訪問陣列元素
- Python - 新增陣列元素
- Python - 刪除陣列元素
- Python - 迴圈遍歷陣列
- Python - 複製陣列
- Python - 反轉陣列
- Python - 排序陣列
- Python - 合併陣列
- Python - 陣列方法
- Python - 陣列練習
- Python 檔案處理
- Python - 檔案處理
- Python - 寫入檔案
- Python - 讀取檔案
- Python - 重新命名和刪除檔案
- Python - 目錄
- Python - 檔案方法
- Python - OS 檔案/目錄方法
- Python - OS 路徑方法
- 面向物件程式設計
- Python - OOPs 概念
- Python - 類 & 物件
- Python - 類屬性
- Python - 類方法
- Python - 靜態方法
- Python - 建構函式
- Python - 訪問修飾符
- Python - 繼承
- Python - 多型
- Python - 方法重寫
- Python - 方法過載
- Python - 動態繫結
- Python - 動態型別
- Python - 抽象
- Python - 封裝
- Python - 介面
- Python - 包
- Python - 內部類
- Python - 匿名類和物件
- Python - 單例類
- Python - 包裝類
- Python - 列舉
- Python - 反射
- Python 錯誤 & 異常
- Python - 語法錯誤
- Python - 異常
- Python - try-except 程式碼塊
- Python - try-finally 程式碼塊
- Python - 丟擲異常
- Python - 異常鏈
- Python - 巢狀 try 程式碼塊
- Python - 使用者自定義異常
- Python - 日誌記錄
- Python - 斷言
- Python - 內建異常
- Python 多執行緒
- Python - 多執行緒
- Python - 執行緒生命週期
- Python - 建立執行緒
- Python - 啟動執行緒
- Python - 執行緒連線
- Python - 執行緒命名
- Python - 執行緒排程
- Python - 執行緒池
- Python - 主執行緒
- Python - 執行緒優先順序
- Python - 守護執行緒
- Python - 執行緒同步
- Python 同步
- Python - 執行緒間通訊
- Python - 執行緒死鎖
- Python - 中斷執行緒
- Python 網路程式設計
- Python - 網路程式設計
- Python - 套接字程式設計
- Python - URL 處理
- Python - 泛型
- Python 庫
- NumPy 教程
- Pandas 教程
- SciPy 教程
- Matplotlib 教程
- Django 教程
- OpenCV 教程
- Python 雜項
- Python - 日期 & 時間
- Python - 數學
- Python - 迭代器
- Python - 生成器
- Python - 閉包
- Python - 裝飾器
- Python - 遞迴
- Python - 正則表示式
- Python - PIP
- Python - 資料庫訪問
- Python - 弱引用
- Python - 序列化
- Python - 模板
- Python - 輸出格式化
- Python - 效能測量
- Python - 資料壓縮
- Python - CGI 程式設計
- Python - XML 處理
- Python - GUI 程式設計
- Python - 命令列引數
- Python - 文件字串
- Python - JSON
- Python - 傳送郵件
- Python - 擴充套件
- Python - 工具/實用程式
- Python - GUIs
- Python 高階概念
- Python - 抽象基類
- Python - 自定義異常
- Python - 高階函式
- Python - 物件內部
- Python - 記憶體管理
- Python - 元類
- Python - 使用元類進行超程式設計
- Python - 模擬和存根
- Python - 猴子補丁
- Python - 訊號處理
- Python - 型別提示
- Python - 自動化教程
- Python - Humanize 包
- Python - 上下文管理器
- Python - 協程
- Python - 描述符
- Python - 診斷和修復記憶體洩漏
- Python - 不可變資料結構
- Python 有用資源
- Python - 問答
- Python - 線上測驗
- Python - 快速指南
- Python - 參考
- Python - 速查表
- Python - 專案
- Python - 有用資源
- Python - 討論
- Python 編譯器
- NumPy 編譯器
- Matplotlib 編譯器
- SciPy 編譯器
Python - 命令列引數
Python 命令列引數
Python 命令列引數提供了一種方便的方式,可以在執行程式時從命令列接受一些資訊。我們通常將這些值與 Python 指令碼的名稱一起傳遞。
要執行 Python 程式,我們在作業系統的命令提示符終端中執行以下命令。例如,在 Windows 中,以下命令輸入到 Windows 命令提示符終端中。
$ python script.py arg1 arg2 arg3
這裡 Python 指令碼名稱為 script.py,其餘三個引數 - arg1 arg2 arg3 是程式的命令列引數。
如果程式需要從使用者那裡接受輸入,則使用 Python 的 input() 函式。當程式從命令列執行時,使用者輸入從命令終端接受。
示例
name = input("Enter your name: ") print ("Hello {}. How are you?".format(name))
程式從命令提示符終端執行如下所示:

在執行時傳遞引數
很多時候,您可能需要將程式要使用的資料放在命令列本身,並在程式內部使用它。在命令列中提供資料的示例可能是 Windows 或 Linux 中的任何 DOS 命令。
在 Windows 中,您使用以下 DOS 命令將檔案 hello.py 重新命名為 hi.py。
C:\Python311>ren hello.py hi.py
在 Linux 中,您可以使用 mv 命令:
$ mv hello.py hi.py
這裡 ren 或 mv 是需要舊檔名和新檔名的命令。由於它們與命令一起放在一行中,因此稱為命令列引數。
您可以從命令列將值傳遞給 Python 程式。Python 將引數收集到列表物件中。Python 的 sys 模組透過 sys.argv 變數提供對任何命令列引數的訪問。sys.argv 是命令列引數的列表,sys.argv[0] 是程式,即指令碼名稱。
示例
hello.py 指令碼使用 input() 函式在指令碼執行後接受使用者輸入。讓我們將其更改為從命令列接受輸入。
import sys print ('argument list', sys.argv) name = sys.argv[1] print ("Hello {}. How are you?".format(name))
從命令列執行程式,如下面的圖所示:

輸出如下所示:
C:\Python311>python hello.py Rajan argument list ['hello.py', 'Rajan'] Hello Rajan. How are you?
命令列引數始終儲存在字串變數中。要將它們用作數字,您可以使用型別轉換函式適當地轉換它們。
示例
在以下示例中,兩個數字作為命令列引數輸入。在程式內部,我們使用 int() 函式將它們解析為整型變數。
import sys print ('argument list', sys.argv) first = int(sys.argv[1]) second = int(sys.argv[2]) print ("sum = {}".format(first+second))
它將產生以下輸出:
C:\Python311>python hello.py 10 20 argument list ['hello.py', '10', '20'] sum = 30
Python 的標準庫包含幾個有用的模組來解析命令列引數和選項:
getopt - C 風格的命令列選項解析器。
argparse - 用於命令列選項、引數和子命令的解析器。
Python getopt 模組
Python 提供了一個 **getopt** 模組,幫助你解析命令列選項和引數。這個模組提供了兩個函式和一個異常來啟用命令列引數解析。
getopt.getopt() 方法
此方法解析命令列選項和引數列表。以下是此方法的簡單語法:
getopt.getopt(args, options, [long_options])
以下是引數的詳細說明:
**args** - 這是要解析的引數列表。
**options** - 這是指令碼想要識別的選項字母字串,需要引數的選項後面應跟一個冒號 (:)。
**long_options** - 這是一個可選引數,如果指定,則必須是一個包含長選項名稱的字串列表,這些選項應得到支援。需要引數的長選項後面應跟一個等號 ('=')。要僅接受長選項,options 應為空字串。
此方法返回一個包含兩個元素的值:第一個是 (option, value) 對的列表,第二個是剝離選項列表後剩下的程式引數列表。
返回的每個選項-值對都將選項作為其第一個元素,短選項字首為連字元 (例如,'-x'),長選項字首為兩個連字元 (例如,'--long-option')。
異常 getopt.GetoptError
當在引數列表中找到無法識別的選項或當需要引數的選項未提供引數時,會引發此異常。
異常的引數是一個字串,指示錯誤的原因。屬性 msg 和 opt 給出了錯誤訊息和相關選項。
示例
假設我們想透過命令列傳遞兩個檔名,並且我們還想提供一個選項來檢查指令碼的使用情況。指令碼的使用方法如下:
usage: test.py -i <inputfile> -o <outputfile>
以下是測試指令碼 test.py:
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 ('Input file is "', inputfile) print ('Output file is "', outputfile) if __name__ == "__main__": main(sys.argv[1:])
現在,按如下方式執行上述指令碼:
$ test.py -h usage: test.py -i <inputfile> -o <outputfile> $ test.py -i BMP -o usage: test.py -i <inputfile> -o <outputfile> $ test.py -i inputfile -o outputfile Input file is " inputfile Output file is " outputfile
Python argparse 模組
**argparse** 模組提供了編寫非常易於使用的命令列介面的工具。它處理如何解析在 **sys.argv** 列表中收集的引數,自動生成幫助資訊,並在給出無效選項時發出錯誤訊息。
設計命令列介面的第一步是設定解析器物件。這是透過 argparse 模組中的 ArgumentParser() 函式完成的。該函式可以將解釋性字串作為 description 引數。
首先,我們的指令碼將在沒有任何引數的情況下從命令列執行。仍然使用解析器物件的 **parse_args()** 方法,它什麼也不做,因為沒有給出任何引數。
import argparse parser=argparse.ArgumentParser(description="sample argument parser") args=parser.parse_args()
當執行上述指令碼時:
C:\Python311>python parser1.py C:\Python311>python parser1.py -h usage: parser1.py [-h] sample argument parser options: -h, --help show this help message and exit
第二個命令列用法給出 **-help** 選項,該選項會生成如下所示的幫助訊息。**-help** 引數預設可用。
現在讓我們定義一個引數,該引數對於指令碼執行是必須的,如果沒有給出,指令碼應該丟擲錯誤。這裡我們透過 add_argument() 方法定義引數 'user'。
import argparse parser=argparse.ArgumentParser(description="sample argument parser") parser.add_argument("user") args=parser.parse_args() if args.user=="Admin": print ("Hello Admin") else: print ("Hello Guest")
此指令碼的幫助資訊現在顯示了一個位置引數,形式為 'user'。程式檢查其值是否為 'Admin',並列印相應的訊息。
C:\Python311>python parser2.py --help usage: parser2.py [-h] user sample argument parser positional arguments: user options: -h, --help show this help message and exit
使用以下命令:
C:\Python311>python parser2.py Admin Hello Admin
但以下用法顯示 Hello Guest 訊息。
C:\Python311>python parser2.py Rajan Hello Guest
add_argument() 方法
我們可以在 add_argument() 方法中為引數分配預設值。
import argparse parser=argparse.ArgumentParser(description="sample argument parser") parser.add_argument("user", nargs='?',default="Admin") args=parser.parse_args() if args.user=="Admin": print ("Hello Admin") else: print ("Hello Guest")
這裡 nargs 是應該消耗的命令列引數的數量。'?'。如果可能,將從命令列消耗一個引數,並將其作為單個專案生成。如果沒有命令列引數,則將生成來自 default 的值。
預設情況下,所有引數都被視為字串。要顯式提及引數的型別,請在 add_argument() 方法中使用 type 引數。所有 Python 資料型別都是 type 的有效值。
import argparse parser=argparse.ArgumentParser(description="add numbers") parser.add_argument("first", type=int) parser.add_argument("second", type=int) args=parser.parse_args() x=args.first y=args.second z=x+y print ('addition of {} and {} = {}'.format(x,y,z))
它將產生以下輸出:
C:\Python311>python parser3.py 10 20 addition of 10 and 20 = 30
在以上示例中,引數是必須的。要新增可選引數,請在其名稱前加上雙破折號 --。在以下情況下,surname 引數是可選的,因為它以雙破折號(--surname)為字首。
import argparse parser=argparse.ArgumentParser() parser.add_argument("name") parser.add_argument("--surname") args=parser.parse_args() print ("My name is ", args.name, end=' ') if args.surname: print (args.surname)
以單破折號為字首的引數的一個字母名稱充當短名稱選項。
C:\Python311>python parser3.py Anup My name is Anup C:\Python311>python parser3.py Anup --surname Gupta My name is Anup Gupta
如果希望引數的值僅來自定義的列表,則將其定義為 choices 引數。
import argparse parser=argparse.ArgumentParser() parser.add_argument("sub", choices=['Physics', 'Maths', 'Biology']) args=parser.parse_args() print ("My subject is ", args.sub)
請注意,如果引數的值不在列表中,則會顯示無效選擇錯誤。
C:\Python311>python parser3.py Physics My subject is Physics C:\Python311>python parser3.py History usage: parser3.py [-h] {Physics,Maths,Biology} parser3.py: error: argument sub: invalid choice: 'History' (choose from 'Physics', 'Maths', 'Biology')