And*_*dré 9 python import-hooks python-3.x python-importlib
使用不推荐使用的模块imp,我可以编写一个自定义导入钩子,在Python导入/执行之前动态修改模块的源代码.给定源代码作为source下面命名的字符串,创建模块所需的基本代码如下:
module = imp.new_module(name)
sys.modules[name] = module
exec(source, module.__dict__)
Run Code Online (Sandbox Code Playgroud)
由于imp被弃用,我想做类似的事情importlib.[编辑:还有其他imp方法需要替换来构建自定义导入钩子 - 所以我要找的答案不仅仅是替换上面的代码.]
但是,我还没弄清楚如何做到这一点.将导入库文件有一个功能,从"规范"创建模块,其中,据我所知,是包括自己的装填重新定义它们,以便能够从字符串创建模块没有明显的方式对象.
我创建了一个最小的例子来证明这一点; 有关详细信息,请参阅自述文件.
Dun*_*nes 14
find_module并且load_module都被弃用了.您需要分别切换到find_spec和(create_module和exec_module)模块.有关详细信息,请参阅importlib 文档
您还需要检查是否要使用a MetaPathFinder或a PathEntryFinder作为系统来调用它们是不同的.也就是说,元路径查找器首先可以覆盖内置模块,而路径条目查找器专门用于找到的模块sys.path.
以下是一个非常基本的进口商,试图替换整个进口机械.它展示了如何使用功能(find_spec,create_module,和exec_module).
import sys
import os.path
from importlib.abc import Loader, MetaPathFinder
from importlib.util import spec_from_file_location
class MyMetaFinder(MetaPathFinder):
def find_spec(self, fullname, path, target=None):
if path is None or path == "":
path = [os.getcwd()] # top level import --
if "." in fullname:
*parents, name = fullname.split(".")
else:
name = fullname
for entry in path:
if os.path.isdir(os.path.join(entry, name)):
# this module has child modules
filename = os.path.join(entry, name, "__init__.py")
submodule_locations = [os.path.join(entry, name)]
else:
filename = os.path.join(entry, name + ".py")
submodule_locations = None
if not os.path.exists(filename):
continue
return spec_from_file_location(fullname, filename, loader=MyLoader(filename),
submodule_search_locations=submodule_locations)
return None # we don't know how to import this
class MyLoader(Loader):
def __init__(self, filename):
self.filename = filename
def create_module(self, spec):
return None # use default module creation semantics
def exec_module(self, module):
with open(self.filename) as f:
data = f.read()
# manipulate data some way...
exec(data, vars(module))
def install():
"""Inserts the finder into the import machinery"""
sys.meta_path.insert(0, MyMetaFinder())
Run Code Online (Sandbox Code Playgroud)
接下来是一个稍微更精致的版本,试图重用更多的导入机器.因此,您只需要定义如何获取模块的源代码.
import sys
from os.path import isdir
from importlib import invalidate_caches
from importlib.abc import SourceLoader
from importlib.machinery import FileFinder
class MyLoader(SourceLoader):
def __init__(self, fullname, path):
self.fullname = fullname
self.path = path
def get_filename(self, fullname):
return self.path
def get_data(self, filename):
"""exec_module is already defined for us, we just have to provide a way
of getting the source code of the module"""
with open(filename) as f:
data = f.read()
# do something with data ...
# eg. ignore it... return "print('hello world')"
return data
loader_details = MyLoader, [".py"]
def install():
# insert the path hook ahead of other path hooks
sys.path_hooks.insert(0, FileFinder.path_hook(loader_details))
# clear any loaders that might already be in use by the FileFinder
sys.path_importer_cache.clear()
invalidate_caches()
Run Code Online (Sandbox Code Playgroud)
另请参阅这个不错的项目https://pypi.org/project/importhook/
pip install importhook
Run Code Online (Sandbox Code Playgroud)
import importhook
# Setup hook to be called any time the `socket` module is imported and loaded into module cache
@importhook.on_import('socket')
def on_socket_import(socket):
new_socket = importhook.copy_module(socket)
setattr(new_socket, 'gethostname', lambda: 'patched-hostname')
return new_socket
# Import module
import socket
# Prints: 'patched-hostname'
print(socket.gethostname())
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4132 次 |
| 最近记录: |