我创建了一个修改过的看门狗示例,以监视已添加到 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