Python重新加载模块不会立即生效 [英] Python reload module does not take effect immediately
问题描述
请参见下面的复制代码.
see the reproduction code below.
处理内存泄漏,我发现reload(module)不会立即生效.
Tracing a memory leak I found that reload(module) does not immediately take effect.
下面的程序应该打印0、1、2、3、4,但是当快速执行时,它会打印诸如0、0、0、3、3之类的序列.将sleep()函数中的时间增加到例如1秒似乎可以解决此问题.
The program below should print 0,1,2,3,4 but, when executed fast it prints sequences like 0,0,0,3,3 and such. Increasing the time in the sleep() function to eg 1 second seems to fix this.
请注意,此代码是更实际的代码的精简版本,仅是为了重现问题,我需要处理现实生活中的情况.
Note that this code is a boiled down version of more practical code just to reproduce the problem, I need to deal with a situation in a real life app.
有人知道如何确保稳定性吗?
Does anybody have an idea how to ensure stability?
我在Windows上,是32位cpython27.
I'm on windows, cpython27 32 bit.
感谢阅读.
# this program assumes folder lib\mymodule exists and contains __init__.py
import time
import io
import gc
modulefile = 'c:\\python27\\lib\\mymodule\\simplemodule.py'
for cnt in range(5):
modulecode = """def runmodule():
return %i
"""%(cnt)
obj = io.open(modulefile, u'wb')
obj.write(modulecode)
obj.close()
if cnt==0:
import mymodule.simplemodule
else:
reload(mymodule.simplemodule)
gc.collect()
print mymodule.simplemodule.runmodule()
time.sleep(0.05)
推荐答案
问题是 pyc 不会再生,除非相对于不讨人喜欢的过时了py 文件.如果以一秒钟的分辨率检查文件修改时间,则可能会忽略您的更新,并且会调用过时的 pyc 而不是更新的源.
The problem is that a pyc won't regenerate unless it is out-of-date with respect to the undelying py file. If the file modification times are checked with a one second resolution, your updates are likely being ignored and the out-of-date pyc is invoked rather than your updated source.
-
尝试在每次 import 或 reload 之间删除 pyc 文件.
或者,您可以设置环境变量PYTHONDONTWRITEBYTECODE=1
.
Alternatively, you can the set the environment variable PYTHONDONTWRITEBYTECODE=1
.
您还可以使用 execfile .
You can also bypass the import logic by using execfile.
这篇关于Python重新加载模块不会立即生效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!