以下代码尝试创建并导入两个模块:
# coding: utf-8
import os
import time
# Remove the modules we're about to create if they already exist
def force_unlink(name):
try:
os.unlink(name)
except OSError:
pass
force_unlink("print1.py")
force_unlink("print1.pyc")
force_unlink("print2.py")
force_unlink("print2.pyc")
time.sleep(1)
# Create module 1 and module 2, then try to import them just afterwards
print("Creating module 1...")
with open("print1.py", "wb+") as fd:
fd.write(b'print("Imported module 1")')
import print1
print("Creating module 2...")
with open("print2.py", "wb+") as fd:
fd.write(b'print("Imported module 2")')
import print2
在Windows上,这两种导入都在Python2(2.7)下工作,但在Python3(3.5和3.6)下不工作:
^{pr2}$在每个import printX
调用之前添加time.sleep(5)
可以使其工作。在
为什么?在
注意:这是一个更简单的版本。
我想我知道发生了什么事。新的python3导入机制缓存它在目录中找到的文件名。当目录的修改时间
mtime
更改时,它将重新加载缓存。在请参见^{} method implementation ,其中包含:
这里的
_path_stat
只是一个os.stat()
调用,但已本地化以避免导入。_fill_cache()
方法执行os.listdir()
调用。在在某些Windows文件系统上,
mtime
的分辨率非常低,最高达2秒。对于您的情况,显然分辨率仍然很低,以至于在您尝试加载第二个模块时,缓存将更新到而不是。虽然NTFS文件系统可以以100ns的增量记录时间,但实际上限制因素似乎是Windows系统时钟,据我所知,它的分辨率通常限制在15毫秒以内。因此,如果在写入print1.py
的15毫秒内写入print2.py
,那么Python不会注意到。在Python提供了清除缓存的方法;使用^{} method ;这将把
FileFinder
实例上的_path_mtime
属性重置回-1
,强制执行一个新的_fill_cache()
调用。在正如职能部门的文件所述:
相关问题 更多 >
编程相关推荐