0

有一个示例(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)是否有任何(跨平台)方法来检测更快速的变化?

4

3 回答 3

1

正确的方法是监视目录而不是轮询更改。

查看FindFirstChangeNotification 函数
Watch a Directory for Changes是一个 Python 实现。

如果目录监视不够准确,那么唯一的选择可能是拦截文件系统调用。

于 2009-10-09T09:42:33.350 回答
1

看门狗: http ://packages.python.org/watchdog/quickstart.html

有一些多平台更改通知是一个很好的项目。

于 2011-12-05T14:27:37.663 回答
0

如果这是 linux,我会使用 inotify。显然有一个 windows inotify 等价物——java jnotify 库已经实现了它——但我不知道是否有 python 实现

于 2009-10-09T09:44:45.080 回答