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/50163834/

相关文章:

python - 大型数据框的总和?

python - 如何用每个唯一值的随机数(随机分类)替换 Pandas 列中的值?

Python错误: Setting an array element with a sequence

python - 欧式距离的高效计算

python - 除以列表数组中的每个值

python - 主题标签是否会干扰正则表达式中的前瞻?

python - 打开扭曲套接字客户端的 Django 命令留下空闲数据库连接

python - 如何使用 pandas 快速将数据框中的字符串更改为整数 ID?

python - 创建每日滚动当前最高值系列

python - 处理从文件读取的文件名中的反斜杠转义