第二个断言失败,表明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)
编辑: - 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/