gpt4 book ai didi

Python 看门狗重复事件

转载 作者:行者123 更新时间:2023-12-02 17:38:22 24 4
gpt4 key购买 nike

我已经创建了一个修改过的看门狗示例,以便监视已添加到 Windows 中特定目录的 .jpg 照片文件。

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

paths = []

xp_mode = 'off'

class FileHandler(FileSystemEventHandler):

def on_created(self, event):
if xp_mode == 'on':
if not event.is_directory and not 'thumbnail' in event.src_path:
print "Created: " + event.src_path
paths.append(event.src_path)

def on_modified(self, event):
if not event.is_directory and not 'thumbnail' in event.src_path:
print "Modified: " + event.src_path
paths.append(event.src_path)

if __name__ == "__main__":
path = 'C:\\'
event_handler = FileHandler()
observer = Observer()
observer.schedule(event_handler, path, recursive=True)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observe r.stop()

observer.join()

我注意到的一件事是,当添加文件时,on_created 和 on_modified 都会被调用!为了解决这个问题,我决定只使用 on_modified 方法。但是,我开始注意到这也会导致多个回调,但这次是 on_modified 方法!

Modified: C:\images\C121211-0008.jpg
Modified: C:\images\C121211-0009.jpg
Modified: C:\images\C121211-0009.jpg <--- What?
Modified: C:\images\C121211-0010.jpg
Modified: C:\images\C121211-0011.jpg
Modified: C:\images\C121211-0012.jpg
Modified: C:\images\C121211-0013.jpg

我一辈子都弄不明白为什么会这样!似乎也不一致。如果有人能阐明这个问题,我们将不胜感激。

有一个类似的帖子,但它是针对 Linux 的:python watchdog modified and created duplicate events

最佳答案

当一个进程写一个文件时,它首先创建它,然后一次写入一个文件的内容。

您看到的是与这些操作相对应的一组事件。有时这些片段的编写速度足够快,以至于 Windows 只为所有这些片段发送一个事件,而其他时候您会收到多个事件。

这是正常的...取决于周围代码需要做什么,保留一组修改后的路径名的而不是列表可能更有意义。

关于Python 看门狗重复事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23859931/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com