joe*_*ker 2 python python-importlib
我有兴趣加载一个 Python 模块,该模块的源代码嵌入在 C 扩展中。应该可以使用 Python 的importlib机制做一些事情importlib.util.spec_from_file_location,这样在调试时就会出现源代码。我将如何实施importlib.util.spec_from_string?
以下是如何定义一个加载器,该加载器从字符串中获取模块的源代码,然后创建模块并将其加载到sys.modules. 如果模块的源代码不在文件中,它可能会很有用。如果已有文件,则直接使用https://docs.python.org/3/library/importlib.html#importing-a-source-file-directly
尽管适用于只需要定义 的inspect.getsource(module)子类,但回溯似乎不愿意显示源代码,直到您继承.importlib.abc.InspectLoaderget_sourcepdbSourceLoader
import sys
import importlib.abc, importlib.util
class StringLoader(importlib.abc.SourceLoader):
def __init__(self, data):
self.data = data
def get_source(self, fullname):
return self.data
def get_data(self, path):
return self.data.encode("utf-8")
def get_filename(self, fullname):
return "<not a real path>/" + fullname + ".py"
module_name = "testmodule"
with open("testmodule.py", "r") as module:
loader = StringLoader(module.read())
spec = importlib.util.spec_from_loader(module_name, loader, origin="built-in")
module = importlib.util.module_from_spec(spec)
sys.modules[module_name] = module
spec.loader.exec_module(module)
Run Code Online (Sandbox Code Playgroud)