Python 将临时文件加载为模块
我似乎无法使用 importlib
加载包含内容的 tempfile
。如果我将内容保存在 python 文件(扩展名为 .py)下,然后提供该文件路径,则效果很好。
有没有办法让 importlib 与临时文件一起工作?
作为参考,请参阅下面的示例代码:
import importlib
import importlib.util
import tempfile
with tempfile.NamedTemporaryFile(mode="w", delete=False) as tf:
tf.write("""
class Test:
def __init__(self):
pass
""")
tf.seek(0)
file_path = tf.name
spec = importlib.util.spec_from_file_location("script", file_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
t = getattr(module, "Test", None)
print(t)
我收到错误:
Traceback (most recent call last):
File "test.py", line 17, in <module>
module = importlib.util.module_from_spec(spec)
File "<frozen importlib._bootstrap>", line 580, in module_from_spec
AttributeError: 'NoneType' object has no attribute 'loader'
I can't seem to load a tempfile
with contents using importlib
. It works fine if I have the content saved under a python file (with .py extension), then provide that file path.
Is there a way to make the importlib work with a tempfile?
For reference, see the sample code below:
import importlib
import importlib.util
import tempfile
with tempfile.NamedTemporaryFile(mode="w", delete=False) as tf:
tf.write("""
class Test:
def __init__(self):
pass
""")
tf.seek(0)
file_path = tf.name
spec = importlib.util.spec_from_file_location("script", file_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
t = getattr(module, "Test", None)
print(t)
I get an error:
Traceback (most recent call last):
File "test.py", line 17, in <module>
module = importlib.util.module_from_spec(spec)
File "<frozen importlib._bootstrap>", line 580, in module_from_spec
AttributeError: 'NoneType' object has no attribute 'loader'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
注意:spec = importlib.util.spec_from_file_location("script", file_path)
规格为无
Note: spec = importlib.util.spec_from_file_location("script", file_path)
spec is None
使用
NamedTemporaryFile(mode="w", suffix=".py", delete=False)
。importlib.util.spec_from_file_location
适用于已知文件扩展名(.py、.so、...),但不适用于其他文件扩展名(.txt...)Use
NamedTemporaryFile(mode="w", suffix=".py", delete=False)
.importlib.util.spec_from_file_location
works for known file name extensions (.py, .so, ...), but not for others (.txt...)