python - importlib.reload 不会重新加载以编程方式生成的文件

标签 python python-3.x

第二个断言失败,表明importlib.reload静静地重新加载修改后的模块失败,谁能解释为什么?

import os
import sys
import tempfile
import importlib


# Create some module and import it
dir = tempfile.TemporaryDirectory()
os.mkdir(os.path.join(dir.name, 'test_package'))
with open(os.path.join(dir.name, '__init__.py'), "w") as f:
    f.write("\n")
with open(os.path.join(dir.name, 'test_package', 'some_module.py'), "w") as f:
    f.write("def a():\n    print(\"old\")\n    return 0\n")
sys.path.insert(0, dir.name)

from test_package import some_module

# Check that imported code works as expected
assert some_module.a() == 0

# Alter module and reload
with open(os.path.join(dir.name, 'test_package', 'some_module.py'), "w") as f:
    f.write("def a():\n    print(\"new\")\n    return 1\n")

importlib.reload(some_module)

# Check wether modifications have been reloaded
assert some_module.a() == 1

sys.path.pop(0)

演示:https://ideone.com/wtaENF

编辑: - python 3.6.1 - archlinux (linux 4.10.13)

最佳答案

以下使用 time.sleep(10) 扩展的代码不会抛出断言错误(安全阈值似乎是一秒)。这解释了为什么重新加载没有按预期工作。所以为什么会引发断言错误的问题的答案是

importlib.reload() uses file timestamp to decide about re-compiling the cached file.

如果代码更新/更改发生得非常快,则缓存文件和脚本文件被认为是同一版本,并且不会重新编译从中重新加载模块的缓存文件。

import os
import sys
import tempfile
import importlib
import time

# Create some module and import it
dir = tempfile.TemporaryDirectory()
os.mkdir(os.path.join(dir.name, 'test_package'))
with open(os.path.join(dir.name, '__init__.py'), "w") as f:
    f.write("\n")
with open(os.path.join(dir.name, 'test_package', 'some_module.py'), "w") as f:
    f.write("def a():\n    print(\"old\")\n    return 0\n")
sys.path.insert(0, dir.name)

from test_package import some_module

# Check that imported code works as expected
assert some_module.a() == 0
time.sleep(10)
# Alter module and reload
with open(os.path.join(dir.name, 'test_package', 'some_module.py'), "w") as f:
    f.write("def a():\n    print(\"new\")\n    return 1\n")

importlib.reload(some_module)

# Check wether modifications have been reloaded
assert some_module.a() == 1

sys.path.pop(0)

关于python - importlib.reload 不会重新加载以编程方式生成的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43801563/

相关文章:

python - 调用 Reddit API 时出现 403 错误。

python - 如何将字典转换为列表?

python - 限制字符串的字符

python - QComboBox调整下拉宽度

Python子进程如何传递subshel​​l参数

python - 如何使 tkinter Canvas 背景透明?

python - 套接字错误 : [Errno 102] Operation not supported on socket

python-3.x - 如何将 x 滚动条添加到 dbc.Card、dash、Python3 的一部分?

Python找不到文件

Python 在本地包中导入本地包时出现问题