您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

python watchdog修改并创建了重复事件

python watchdog修改并创建了重复事件

简短的回答: f = open(... , 'w')生成FileCreatedEventf.flush()或者f.close()可以生成FileModifiedEvent。是的,创建文件通常会同时生成FileCreatedEventFileModifiedEvents

是否可以安全地忽略FileCreatedEvents取决于您要执行的操作。如果您有兴趣在创建文件时做出反应,则需要处理FileCreatedEvents,并且可能忽略FileModifiedEvents,因为在修改文件时可以生成FileModifiedEvents,而无需生成FileCreatedEvents。

尝试使用规范的看门狗脚本(如下),并且所有内容都应该更加清晰。

长答案:要查看发生了什么,请直接从docs运行规范的看门狗程序:

import sys
import time
import logging
from watchdog.observers import Observer
from watchdog.events import LoggingEventHandler

if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO,
                        format='%(asctime)s - %(message)s',
                        datefmt='%Y-%m-%d %H:%M:%s')
    path = sys.argv[1] if len(sys.argv) > 1 else '.'
    event_handler = LoggingEventHandler()
    observer = Observer()
    observer.schedule(event_handler, path, recursive=True)
    observer.start()
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

从终端:

% mkdir ~/tmp
% cd ~/tmp
% script.py

现在,当您在w模式下打开文件时,在Python解释器中:

In [126]: f = open('/home/unutbu/tmp/foobar', 'w')

终端打印

2014-02-05 16:29:34 - <FileCreatedEvent: src_path=/home/unutbu/tmp/foobar>

当您写入文件时,看门狗不报告任何事件:

In [127]: f.write('Hi')

但是当你冲洗时

In [128]: f.flush()

它报告一个FileModifiedEvent:

2014-02-05 16:29:55 - <FileModifiedEvent: src_path=/home/unutbu/tmp/foobar>

如果您将更多内容写入文件

In [129]: f.write(' there')

同样,关闭文件时将报告FileModifiedEvent,因为更多的输出将刷新到磁盘:

In [130]: f.close()

2014-02-05 16:30:12 - <FileModifiedEvent: src_path=/home/unutbu/tmp/foobar>
python 2022/1/1 18:25:37 有447人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶