use*_*638 0 python pywin32 python-2.7 python-watchdog
我创建了一个修改过的看门狗示例,以便监视已添加到 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()
Run Code Online (Sandbox Code Playgroud)
我注意到的一件事是,当添加文件时,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
Run Code Online (Sandbox Code Playgroud)
我一生都无法弄清楚为什么会发生这种情况!似乎也不一致。如果有人可以对这个问题有所了解,我们将不胜感激。
有一个类似的帖子,但它是针对Linux的:python watchdog modified and created duplicate events
当一个进程写入一个文件时,它首先创建它,然后一次写入一段内容。
您看到的是与这些操作相对应的一组事件。有时这些片段编写得足够快,以至于 Windows 只为所有这些片段发送一个事件,而有时您会收到多个事件。
这是正常的……取决于周围代码需要做什么,保留 a setof 修改后的路径名而不是list.
| 归档时间: |
|
| 查看次数: |
2852 次 |
| 最近记录: |