Python 将临时文件加载为模块

问题描述 投票:0回答:2

我似乎无法使用

tempfile
加载
importlib
的内容。如果我将内容保存在 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'
python python-import python-importlib
2个回答
0
投票

注意:spec = importlib.util.spec_from_file_location("script", file_path)
规格为无

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)
    print(f'{spec=}')
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)

    t = getattr(module, "Test", None)
    print(t)


0
投票

使用

NamedTemporaryFile(mode="w", suffix=".py", delete=False)

importlib.util.spec_from_file_location
适用于已知文件扩展名(.py、.so、...),但不适用于其他文件扩展名(.txt...)

© www.soinside.com 2019 - 2024. All rights reserved.