【问题标题】:Python watchdog: ignoring duplicate eventsPython看门狗:忽略重复事件
【发布时间】:2018-11-07 13:14:31
【问题描述】:

我正在尝试设置看门狗,以便监控 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()

【问题讨论】:

    标签: python watchdog python-watchdog


    【解决方案1】:

    一种天真的方法是将文件/日期存储在字典中,然后在处理事件之前检查时间/文件源是否在字典中。

    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 来缓存结果,这样字典会更小一些。

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-04-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-03
        相关资源
        最近更新 更多