新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
創(chuàng)新互聯(lián)Python教程:python探針如何實現(xiàn)
1、探針importhook的功能可以通過sys.meta_path來實現(xiàn)。

創(chuàng)新互聯(lián)是一家專注于成都網(wǎng)站建設、成都做網(wǎng)站與策劃設計,鶴山網(wǎng)站建設哪家好?創(chuàng)新互聯(lián)做網(wǎng)站,專注于網(wǎng)站建設10年,網(wǎng)設計領域的專業(yè)建站公司;建站業(yè)務涵蓋:鶴山等地區(qū)。鶴山做網(wǎng)站價格咨詢:028-86922220
2、當執(zhí)行import相關操作時,import相關庫將根據(jù)sys.meta_path定義的對象進行更改。
sys.meta_path中的對象需要實現(xiàn)find_module方法。這種find_module方法返回None或實現(xiàn)load_module方法的對象。我們可以通過這個對象在import中替換一些圖書館的相關方法。簡單用法如下。通過hooktime.sleep,可以在sleep中打印時間。
實例
import importlib
import sys
from functools import wraps
def func_wrapper(func):
"""這里通過一個裝飾器來達到貍貓換太子和獲取數(shù)據(jù)的效果"""
@wraps(func)
def wrapper(*args, **kwargs):
# 記錄開始時間
start = time.time()
result = func(*args, **kwargs)
# 統(tǒng)計消耗時間
end = time.time()
print(f"speed time:{end - start}")
return result
return wrapper
class MetaPathFinder:
def find_module(self, fullname, path=None):
# 執(zhí)行時可以看出來在import哪些模塊
print(f'find module:{path}:{fullname}')
return MetaPathLoader()
class MetaPathLoader:
def load_module(self, fullname):
# import的模塊都會存放在sys.modules里面, 通過判斷可以減少重復import
if fullname in sys.modules:
return sys.modules[fullname]
# 防止遞歸調用
finder = sys.meta_path.pop(0)
# 導入 module
module = importlib.import_module(fullname)
if fullname == 'time':
# 替換函數(shù)
module.sleep = func_wrapper(module.sleep)
sys.meta_path.insert(0, finder)
return module
sys.meta_path.insert(0, MetaPathFinder())
if __name__ == '__main__':
import time
time.sleep(1)
# 輸出示例:
# find module:datetime
# find module:time
# load module:time
# find module:math
# find module:_datetime
# speed time:1.00073385238647468
以上就是python探針的實現(xiàn),希望對大家有所幫助。更多Python學習指路:創(chuàng)新互聯(lián)Python教程
本文教程操作環(huán)境:windows7系統(tǒng)、Python 3.9.1,DELL G3電腦。
網(wǎng)頁名稱:創(chuàng)新互聯(lián)Python教程:python探針如何實現(xiàn)
網(wǎng)頁地址:http://fisionsoft.com.cn/article/dhhjiss.html


咨詢
建站咨詢
