find_module
并且load_module
都已弃用。您需要分别切换到find_spec
和 (create_module
和exec_module
) 模块。有关详细信息,请参阅importlib
文档。
您还需要检查是否要使用 aMetaPathFinder
或 aPathEntryFinder
因为调用它们的系统是不同的。也就是说,元路径查找器首先出现并且可以覆盖内置模块,而路径条目查找器专门用于在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())
接下来是一个稍微更精致的版本,它试图重用更多的进口机器。因此,您只需要定义如何获取模块的来源。
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()