Python 看门狗:忽略重复事件

Python watchdog: ignoring duplicate events

我正在尝试设置看门狗,以便我可以监视对 JavaScript 文件的更改。但是当单个文件被修改时,你总是会得到重复的事件。

我想对其进行设置,以便在修改文件时查看事件发生的时间,如果它与上一个事件的时间相同,则它不执行任何操作。这样它就可以忽略重复的事件。有没有办法做到这一点,并始终将上一个事件的时间存储在一个变量中?

import time
from os import path
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler


class MyHandler(FileSystemEventHandler):
    def on_modified(self, event):
        print(time.ctime(), f'path : {event.src_path}')


if __name__ == "__main__":
    event_handler = MyHandler()
    observer = Observer()
    observer.schedule(event_handler, path=path.join(path.dirname(__file__), 'static/js'), recursive=False)
    observer.start()

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

一种简单的方法是将 files/dates 存储在字典中,然后在处理事件之前检查 time/file 源是否在字典中。

class MyHandler(FileSystemEventHandler):
    file_cache = {}

    def on_modified(self, event):
        seconds = int(time.time())
        key = (seconds, event.src_path)
        if key in self.file_cache:
            return
        self.file_cache[key] = True
        # Process the file

如果您担心事件的数量,您可以尝试使用 cachetools 来缓存结果,以便字典保持较小。

我不确定其他人。但我采用了 on_closed 事件而不是修改,因为通常文件编写器将在完成写入文件后关闭文件(至少在我的情况下)。 请注意,on_closed 事件似乎不会在 win32 系统上触发。