python 监控文件变化 - python watchdog模块使用方法

很多时候我们希望根据一个文件目录下文件和文件夹的变化情况,做出相应的响应。当然我们无需每时每刻都去扫描该文件目录,python watchdog 模块提供了这方面的功能。Watchdog用于监控一个文件目录下的文件和文件夹的变动,包括文件和文件夹的增删改,移动等。

watchdog是github上的一个开源项目,源码见这里,采用观察者模式。watchdog 提供了对于不同操作系统的支持,在源码路径中master/src/watchdog/observers/__init__.py的注释说明了对于如下操作系统的支持:

============== ================================ ==============================
Class          Platforms                        Note
============== ================================ ==============================
|Inotify|      Linux 2.6.13+                    ``inotify(7)`` based observer
|FSEvents|     Mac OS X                         FSEvents based observer
|Kqueue|       Mac OS X and BSD with kqueue(2)  ``kqueue(2)`` based observer
|WinApi|       MS Windows                       Windows API-based observer
|Polling|      Any                              fallback implementation
============== ================================ ==============================

可以看到对于包括window,linux以及MAC os都提供了支持,可以放心使用。

如下是对于该模块的使用示例:

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

class FileEventHandler(FileSystemEventHandler):
    def __init__(self):
        FileSystemEventHandler.__init__(self)

    def on_moved(self, event):
        if event.is_directory:
            print("directory moved from {} to {}".format(event.src_path,event.dest_path))
        else:
            print("file moved from {} to {}".format(event.src_path,event.dest_path))
            self.task(filName = event.dest_path)

    def on_created(self, event):
        if event.is_directory:
            print("directory created:{}".format(event.src_path))
        else:
            print("file created:{}".format(event.src_path))

    def on_deleted(self, event):
        if event.is_directory:
            print("directory deleted:{}".format(event.src_path))
        else:
            print("file deleted:{}".format(event.src_path))

    def on_modified(self, event):
        if event.is_directory:
            print("directory modified:{}".format(event.src_path))
        else:
            print("file modified:{}".format(event.src_path))

    def task(self,filName):
        print(filename)
        #具体任务

if __name__ == "__main__":
    observer = Observer()
    event_handler = FileEventHandler()
    filePath = '/data/pcap'
    observer.schedule(event_handler,filePath,True)
    observer.start()

    time.sleep(100)

    observer.stop()
    observer.join()

可以看到使用起来也是非常的简单:

1,重新定义一个类继承FileSystemEventHandler类,重载四个事件函数即可。这四个函数对应的是文件的增删改,移动等事件。

2,以on_moved函数为例,在该函数中处理对于文件移动事件的响应,我调用的是task函数,该函数可以根据实际的需求进行修改。

3,将新类的对象,监控的文件目录作为参数传入observer.schedule函数,filePath即监控的文件目录,event_handler对象对于文件事件做出处理。

4,observer.start()启动之后,一直是监听状态,除非显示的退出。我的示例程序中在监听100s之后退出,可以根据自身情况进行修改。

使用过程中的注意事项:

1,文件创建的动作其实会触发多种事件,包括FileCreatedEvent以及FileModifiedEvent时间,触发on_created以及on_modified函数,这是需要注意的。原因在于f = open(… , ‘w’) 这样文件创建动作会触发FileCreatedEvent事件,执行on_created函数; 在往文件些数据的时候例如f.flush() 和f.close()操作 会触发FileModifiedEvent事件,执行on_modified函数。

2,前面也提到不同的操作系统平台基于不同的observer,在文件处理方面也可能会存在差异,因此对于不同的平台,最好详细测试一下文件的创建,写入,关闭的个操作会触发什么事件。

3,我的业务场景是监控文件夹下面pcap报文的情况,并解码报文。我在Linux平台上的策略是在写数据的时候,我的文件名是xxx,在文件写完之后,我将文件名修改成为xxx.pcap。这个时候文件名的修改会触发文件移动事件,那么这个时候我在on_moved函数中执行对于pcap报文的解析就可以了。对于文件创建写入引发的修改和创建事件忽略即可。

4,在实际处理过程中watchdog的对于事件的响应还是非常的及时。

上述就是watchdog的简单的使用经验。

本文为CSDN村中少年原创文章,转载记得加上原创出处,博主链接这里

发布了132 篇原创文章 · 获赞 183 · 访问量 28万+

猜你喜欢

转载自blog.csdn.net/javajiawei/article/details/100927491