栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

文件系统监控--Python Watchdog模块监控文件时出现重复输出的问题

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

文件系统监控--Python Watchdog模块监控文件时出现重复输出的问题

问题描述

利用Watchdog模块监控目录文件的变化时,会出现以下问题:

1.创建文件时,监控输出为:文件的创建-文件的修改

2.修改文件时,监控输出为:文件的修改-文件的修改

当前监控的目录:./
# 新建文本文档的输出
file created:./新建文本文档.txt
file modified:./新建文本文档.txt
# 修改 新建文本文档的输出
file modified:./新建文本文档.txt
file modified:./新建文本文档.txt
# 修改 test.txt的输出
file modified:./test.txt
file modified:./test.txt

原因分析:

输出重复问题,不是watchdog模块本身的原因.
当写入文件时,它首先创建该文件,然后一次写入一个内容。您所看到的是与这些操作对应的一组事件。有时,这些片段的编写速度足够快,以至于Windows仅为所有片段发送一个事件,而其他时候则获得多个事件。

参考链接

https://blog.csdn.net/Huomaotong/article/details/121187172

https://blog.csdn.net/weixin_39559277/article/details/110903484


解决方案:

问题分析:

第一点:我们对同一文件进行一个操作,而操作系统在极短时间内进行了多项指令,于是watchdog模块的监测输出重复.  

第二点:我们需要根据watchdog的输出,来执行后续的任务..watchdog的重复输出导致任务的输出重复.

解决方案:

问题分析中涉及四个方面: 文件/时间/watchdog/任务块

将任务块从watchdog类中分离出来,通过 对比文件是否重复 和 监测时间间隔 来决定任务块的执行.  具体实现方式见下面代码.(提示:代码中只涉及文件的创建和修改)

import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler


path_reference = None  # 文件参照:判断监测输出是不是指向同一文件
time_reference = None  # 时间参照:增加time模块,可以监测对同一文件不同时间的更改


def seng_mail(event, path):  # 任务块
    global path_reference,time_reference
    time_now=time.time()
    if path_reference != path or time_now-time_reference > 3: # 判断语句,时间间隔可更改
        print("file {0}:{1}".format(event, path))
        print('要执行的任务块')
    path_reference = path
    time_reference = time_now


class FileEventHandler(FileSystemEventHandler):  # watchdog类
    def __init__(self):
        FileSystemEventHandler.__init__(self)

    def on_created(self, event):  
        if event.is_directory:
            print("directory created:{0}".format(event.src_path))
        else:
            seng_mail('created', event.src_path) # 调用任务块

    def on_modified(self, event):  
        if event.is_directory:
            print("directory modified:{0}".format(event.src_path))
        else:
            seng_mail('modified', event.src_path) # 调用任务块


if __name__ == "__main__":
    observer = Observer()
    event_handler = FileEventHandler()
    dir = './'
    observer.schedule(event_handler, dir, False)
    print(f"当前监控的目录:{dir}")
    observer.start()
    observer.join()

暑期编程PK赛 得CSDN机械键盘等精美礼品!
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1015542.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号