一、argparse模塊簡介
Python argparse是一個命令行解析庫,支持腳本參數、子命令和類型檢查功能。argparse最常用的作用是將命令行參數轉換為Python中易於操作的對象。
argparse主要包含ArgumentParser類和一些其他有用的子模塊,常見的子模塊有argparse.ArgumentParser.add_argument()方法、argparse.ArgumentParser.parse_args()方法和argparse.Namespace類。
二、ArgumentParser類詳解
argparse.ArgumentParser類用於解析命令行參數,它提供了add_argument()方法來定義命令行參數的類型、默認值、幫助信息、特定行為和許多其他屬性。
add_argument()方法包含多個參數,最常用的參數如下:
- name or flags(參數名):字符串或列表,用來定義參數的名字或選項(例如”–input” 或 “-i”)。參數名和選項名必須以”–“或”-“開頭。
- type(參數類型):指定參數的類型,如int、float、str和bool。
- default(默認值):指定參數的默認值,如果沒有設置此參數,則表示參數是必需的。
- help(幫助信息):用來描述參數的幫助信息,當用戶輸入”–help”時,會顯示此信息。
- action(特定行為):定義參數的特定行為,如store、store_true、store_false等。
- nargs:用於指定參數數量,如”?”表示0或1個參數,”*”表示0或多個參數,”+”表示1或多個參數。
import argparse
parser = argparse.ArgumentParser(description='Example usage of argparse')
parser.add_argument('input', help='input file path') # 必需參數
parser.add_argument('--output', help='output file path') # 可選參數
parser.add_argument('--verbose', action='store_true', help='whether to output verbose information') # 可選開關參數
args = parser.parse_args()
print(args.input)
print(args.output)
print(args.verbose)
三、parse_args()方法詳解
argparse.ArgumentParser.parse_args()方法用於解析命令行參數,並返回一個包含所有參數值的命名空間對象。
使用此方法時,需要注意以下幾點:
- 參數的輸入方式通常是使用空格分隔的方式,如”–input /path/to/file.txt”。
- 如果輸入的參數無法解析或不符合規定,則會引發異常,可以使用”–help”選項獲取更多信息。
import argparse
parser = argparse.ArgumentParser(description='Example usage of argparse')
parser.add_argument('input', help='input file path') # 必需參數
parser.add_argument('--output', help='output file path') # 可選參數
parser.add_argument('--verbose', action='store_true', help='whether to output verbose information') # 可選開關參數
args = parser.parse_args()
print(args.input)
print(args.output)
print(args.verbose)
四、Namespace類詳解
argparse.Namespace類是一個簡單的命名空間類,用於存儲參數值。
當使用argparse.ArgumentParser.parse_args()方法解析命令行參數時,返回的就是一個由argparse.Namespace類實例化的對象。
這個類沒有實例化構造函數,可以通過訪問對象屬性來設置和獲取參數值。
import argparse
parser = argparse.ArgumentParser(description='Example usage of argparse')
parser.add_argument('input', help='input file path') # 必需參數
parser.add_argument('--output', help='output file path') # 可選參數
parser.add_argument('--verbose', action='store_true', help='whether to output verbose information') # 可選開關參數
args = parser.parse_args()
print(args.input)
print(args.output)
print(args.verbose)
五、小結
本文對Python argparse模塊進行了詳細的介紹,主要包含ArgumentParser類、parse_args()方法和Namespace類的詳細解釋。當我們需要從命令行讀取參數時,argparse模塊可以幫助我們簡化代碼,並提供更友好的交互方式。
原創文章,作者:ZXCIG,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/332729.html