python watchdog 修改并创建重复事件

标签 python watchdog

在 Ubuntu 上运行,每次我创建一个文件时,我都会得到一个修改和创建的事件。

这是设计使然还是我做错了什么?

我正在使用事件处理程序类 PatternMatchingEventHandler

event_handler = MediaFileHandler(ignore_directories=True) 
observer = Observer() 
observer.schedule(event_handler, path=directory, recursive=True) 
observer.start()

如果这是正确的行为,我可以安全地忽略创建的事件吗?

最佳答案

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

您是否可以安全地忽略 FileCreatedEvents 取决于您尝试做什么。如果您有兴趣在创建文件时使用react,那么您需要处理 FileCreatedEvents,并且可能忽略 FileModifiedEvents,因为在修改文件时可能会生成 FileModifiedEvents 而不会生成 FileCreatedEvents。

尝试一下规范的看门狗脚本(如下),一切都应该更清楚。


长答案:要查看发生了什么,请运行规范的看门狗程序 straight from the 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 watchdog 修改并创建重复事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21587415/

相关文章:

c - STM32 Discovery 看门狗定时器的中断服务例程

Linux : Watchdog always busy

arduino - 如何让 LED 每 n 秒闪烁一次而不会出现延迟?

python - 使用 Python 在目录中监视文件,然后使用 POST 请求发送文件修改数据

python - imaplib 和 poplib python 的证书颁发机构

python - pip install FuzzySet 在 OSX 上失败 - virtualenv with python3

python - 如何捕获在 IIS、FastCGI 和 WSGI 下运行的 Python 进程的 STDOUT?

python - 创建对变量的引用(类似于PHP的 "=&")?

python - 如何从没有特定字符的文本文件中打印一行

Python看门狗应用程序