Get the App
SLTechnology News&Howtos  ›  Development  › 

How to realize python probe

Shulou Source: shulou.com Published: 2022-06-03 17:41:29 09月26日 Update

This article will explain in detail how to implement python probes for everyone. Xiaobian thinks it is quite practical, so share it with you for reference. I hope you can gain something after reading this article.

1. The function of probe importhook can be realized through sys.meta_path.

When import-dependent operations are performed, import-dependent libraries change based on objects defined by sys.meta_path.

Objects in sys.meta_path need to implement the find_module method. This find_module method returns None or an object that implements the load_module method. We can replace some library related methods in import with this object. Simple usage is as follows. With hooktime.sleep, you can print the time in sleep.

examples

import importlibimport sysfrom functools import wraps def func_wrapper(func): """Here, a decorator is used to achieve the effect of exchanging raccoon for prince and obtaining data""" @wraps(func) def wrapper(*args, **kwargs): #Record Start Time start = time.time() result = func(*args, **kwargs) #Statistics elapsed time end = time.time() print(f"speed time:{end - start}") return result return wrapper class MetaPathFinder: def find_module(self, fullname, path=None): #When executing, you can see which modules are imported print(f'find module:{path}:{fullname}') return MetaPathLoader() class MetaPathLoader: def load_module(self, fullname): # import modules will be stored in sys.modules, through judgment can reduce duplication import if fullname in sys.modules: return sys.modules[fullname] #Prevent Recursive Calls finder = sys.meta_path.pop(0) #Import module module = importlib.import_module(fullname) if fullname == 'time': #Replacement function 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) #Output example:# find module:datetime# find module:time# load module:time# find module:math# find module:_datetime# speed time:1.00073385238647468 About "python probe how to achieve" This article is shared here, I hope the above content can be of some help to everyone, so that you can learn more knowledge, if you think the article is good, please share it to let more people see.

Tags: Objects methods probes time articles can be passed more modules good practical content functions functions books libraries examples effects data articles raccoons Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Microsoft MariaDB Shulou Tech Info Shulou Information MySQL