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

时间:2017-05-05 09:38:33

标签: 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)

1 个答案:

答案 0 :(得分:2)

public function store(Request $request) { $data = $request->all(); $list = array_get($data, 'list', 'default value'); $total_amount = array_get($data, 'total_amount', 0); ... return $whatever; } 扩展的以下代码不会抛出断言错误(安全阈值似乎是一秒)。这解释了为什么重新加载不能按预期工作的原因。因此,提出断言错误的问题的答案是

  

time.sleep(10)使用文件时间戳来决定重新编译缓存的文件。

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

importlib.reload()
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)