品易云推流 关闭
文章详情页
文章 > Python基础教程 > python探针如何实现

python探针如何实现

python探针

头像

小妮浅浅

2021-09-25 09:33:142750浏览 · 0收藏 · 0评论

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中打印时间。

实例

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探针的实现,希望对大家有所帮助。更多Python学习指路:python基础教程

本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

关注

关注公众号,随时随地在线学习

本教程部分素材来源于网络,版权问题联系站长!

底部广告图