Python中的inspect
模塊解析
Python的inspect
模塊是一個強大的內省工具,允許開發者檢查(inspect)活動對象和源代碼。它提供了一系列函數,用於獲取信息關於正在運行的程序和調用堆棧,非常適合進行調試和動態分析。本文將通過介紹inspect
模塊的關鍵功能,並結合實際案例代碼,來探索其在日常開發中的應用。
常用方法
1. 獲取當前執行的函數或方法名、文件路徑【並不是調用方】
在日誌記錄或調試時,知道當前執行的函數名是非常有用的
import inspect
def who_am_i():
# 輸出當前文件絕對路徑
print(inspect.currentframe().f_code.co_filename)
return inspect.currentframe().f_code.co_name
print(who_am_i()) # 輸出: who_am_i
個人認爲比較有用的就是 co_filename、co_name
2. 獲取調用者信息
獲取當前函數或方法的調用者信息
import inspect
def caller_info():
frame = inspect.currentframe().f_back
print(f調用者 {frame.f_code.co_filename} 調用行號 d{frame.f_lineno}")
def test():
caller_info() # 調用以獲取調用者信息
test()
這個例子顯示瞭如何獲取調用當前函數的代碼位置,非常有助於調試複雜的調用鏈
3. 查看函數參數
inspect
模塊可以用來檢查函數或方法的參數,這對於動態分析和生成文檔非常有用
import inspect
def sample_function(name, age=25):
pass
sig = inspect.signature(sample_function)
print(sig) # 輸出: (name, age=25)
4. 獲取源代碼
inspect
還可以用來獲取函數、類或模塊的源代碼
import inspect
def my_function():
"""A simple function."""
pass
print(inspect.getsource(my_function))
5. 檢查類和實例
inspect
模塊提供了多種方式來檢查類和實例,比如獲取類的所有方法、屬性等
class MyClass:
def method_one(self):
pass
def method_two(self):
pass
# 獲取類的所有成員方法
methods = inspect.getmembers(MyClass, predicate=inspect.isfunction)
print(methods) # 輸出 MyClass 中定義的方法
實際案例:自動化場景下的應用
一個常見的使用場景是動態地調用函數或方法,並基於它們的簽名自動生成文檔。
def test():
# 獲取調用方
frame = inspect.currentframe().f_back
# 獲取調用方文件絕對路徑
caller_file = inspect.getfile(frame)
# 這種方式也可以
caller_file = frame.f_code.co_filename
...
params = [
caller_file,
"--env-data",
env_data.json(),
f"--count={count}",
"-m",
mark,
]
一個基於 Pytest 自動化測試項目
- 每個 py 模塊都會調用這個方法來執行 Pytest 命令來跑測試用例
- 那怎麼才能準確知道要跑哪個文件呢?
- 通過第一、二行代碼即可
更便捷的方式