Python的imp.reload()函数不起作用? [英] Python's imp.reload() function is not working?
问题描述
以下是一个简明的例子:
Here's a concise example:
x.py:
class x:
var = 'from x.py'
y.py:
class x:
var = 'from y.py'
test.py
import imp
def write_module(filename):
fp = open('z.py', 'w')
fp.write(open(filename).read())
fp.close()
write_module('x.py')
import z
print(z.x.var) # Prints 'from x.py'
write_module('y.py')
imp.reload(z)
print(z.x.var) # Prints 'from x.py'
我不确定为什么两个打印语句都是一样的。如何让python在reload()之后使用类x的新定义?
I'm not sure why both print statements are the same. How can I make python use the new definition of class x after reload()?
推荐答案
这是因为文件创建日期( z.py
及其编译对应 z.pyc
)是相同的,因此Python认为该文件未更改且不会重新编译它。
This happens because the file creation dates (of z.py
and its compiled counterpart z.pyc
) are identical, so Python thinks that the file is unchanged and doesn't recompile it.
实际上,当我尝试并重新尝试你的代码时,它曾经按预期工作 - 可能是因为这两个文件碰巧是在系统时钟的两侧创建的第二次转换。
Actually, when I was trying and re-trying your code, it once worked as expected - probably because the two files happened to be created on either side of the system clock's second-changeover.
import imp
import time
def write_module(filename):
fp = open('z.py', 'w')
fp.write(open(filename).read())
fp.close()
write_module('x.py')
import z
print(z.x.var) # Prints 'from x.py'
time.sleep(1) # Wait one second
write_module('y.py')
imp.reload(z)
print(z.x.var) # Prints 'from y.py'
显示预期结果。
这篇关于Python的imp.reload()函数不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!