python探针如何实现

344次阅读
没有评论

python探针如何实现

1、探针importhook的功能可以通过sys.meta_path来实现。

2、当执行import相关操作时,import相关库将根据sys.meta_path定义的对象进行更改。

sys.meta_path中的对象需要实现find_module方法。这种find_module方法返回None或实现load_module方法的对象。我们可以通过这个对象在import中替换一些图书馆的相关方法。简单用法如下。通过hooktime.sleep,可以在sleep中打印时间。

python探针实例

import importlib
import sys
from functools import wraps
 
 
def func_wrapper(func):
    """这里通过一个装饰器来达到狸猫换太子和获取数据的效果"""
    @wraps(func)
    def wrapper(*args, **kwargs):
        # 记录开始时间
        start = time.time()
        result = func(*args, **kwargs)
        # 统计消耗时间
        end = time.time()
        print(f"speed time:{end - start}")
        return result
    return wrapper
 
 
class MetaPathFinder:
 
    def find_module(self, fullname, path=None):
        # 执行时可以看出来在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':
            # 替换函数
            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探针的实现,希望对大家有所帮助。

神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2022-06-12发表,共计1530字。
新手QQ群:570568346,欢迎进群讨论 Python51学习