【问题标题】:python watchdog modified and created duplicate eventspython看门狗修改并创建重复事件
【发布时间】:2014-02-05 20:09:20
【问题描述】:

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

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

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

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

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

【问题讨论】:

    标签: python watchdog


    【解决方案1】:

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

    您是否可以安全地忽略 FileCreatedEvents 取决于您要执行的操作。如果您有兴趣在创建文件时做出反应,那么您需要处理 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 
    

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

    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>
    

    【讨论】:

    • 好的,谢谢。这就是我在想什么。我感谢详细的回答。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-23
    • 1970-01-01
    相关资源
    最近更新 更多