Windows上stat mtime的准确性
这里有一段示例代码(用Python写的),用来检查一个文件夹是否发生了变化:
import os
def watch(path, fdict):
"""Checks a directory and children for changes"""
changed = []
for root, dirs, files in os.walk(path):
for f in files:
abspath = os.path.abspath(os.path.join(root, f))
new_mtime = os.stat(abspath).st_mtime
if not fdict.has_key(abspath) or new_mtime > fdict[abspath]:
changed.append(abspath)
fdict[abspath] = new_mtime
return fdict, changed
但是,配套的单元测试有时候会随机失败,除非我在代码中加上至少2秒的暂停:
import unittest
import project_creator
import os
import time
class tests(unittest.TestCase):
def setUp(self):
os.makedirs('autotest')
f = open(os.path.join('autotest', 'new_file.txt'), 'w')
f.write('New file')
def tearDown(self):
os.unlink(os.path.join('autotest', 'new_file.txt'))
os.rmdir('autotest')
def test_amend_file(self):
changed = project_creator.watch('autotest', {})
time.sleep(2)
f = open(os.path.join('autotest', 'new_file.txt'), 'a')
f.write('\nA change!')
f.close()
changed = project_creator.watch('autotest', changed[0])
self.assertEqual(changed[1], [os.path.abspath(os.path.join('autotest', 'new_file.txt'))])
if __name__ == '__main__':
unittest.main()
那这个stat函数真的只能精确到1秒吗?(补充:显然是的,尤其是在FAT文件系统上)有没有什么方法可以更快地检测变化,且能在不同平台上都能用呢?
3 个回答
0
如果这是在Linux系统上,我会用inotify这个工具。听说在Windows上也有类似的工具,叫做jnotify库,它是用Java写的。不过我不太清楚有没有用Python实现的版本。
1
1
正确的方法是监视一个文件夹,而不是不断地去检查有没有变化。
你可以看看这个链接:FindFirstChangeNotification 函数。
还有这个链接:监视文件夹的变化,这是一个用Python实现的例子。
如果监视文件夹的方式不够准确,那么可能唯一的替代方法就是拦截文件系统的调用。