python中文件变化监控示例(watchdog)
Python  /  管理员 发布于 7年前   184
在python中文件监控主要有两个库,一个是pyinotify ( https://github.com/seb-m/pyinotify/wiki ),一个是watchdog(http://pythonhosted.org/watchdog/)。pyinotify依赖于Linux平台的inotify,后者则对不同平台的的事件都进行了封装。因为我主要用于Windows平台,所以下面着重介绍watchdog(推荐大家阅读一下watchdog实现源码,有利于深刻的理解其中的原理)。
watchdog在不同的平台使用不同的方法进行文件检测。在init.py中发现了如下注释:
|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|(ReadDirectoryChangesW) MS Windows Windows API-based observer|Polling| Any fallback implementation
给出示例代码如下:
from watchdog.observers import Observerfrom watchdog.events import *import timeclass FileEventHandler(FileSystemEventHandler):def __init__(self):FileSystemEventHandler.__init__(self)def on_moved(self, event):if event.is_directory:print("directory moved from {0} to {1}".format(event.src_path,event.dest_path))else:print("file moved from {0} to {1}".format(event.src_path,event.dest_path))def on_created(self, event):if event.is_directory:print("directory created:{0}".format(event.src_path))else:print("file created:{0}".format(event.src_path))def on_deleted(self, event):if event.is_directory:print("directory deleted:{0}".format(event.src_path))else:print("file deleted:{0}".format(event.src_path))def on_modified(self, event):if event.is_directory:print("directory modified:{0}".format(event.src_path))else:print("file modified:{0}".format(event.src_path))if __name__ == "__main__":observer = Observer()event_handler = FileEventHandler()observer.schedule(event_handler,"d:/dcm",True)observer.start()try:while True:time.sleep(1)except KeyboardInterrupt:observer.stop()observer.join()
watchdog主要采用观察者模型(废话,从变量命名就可以看出来)。主要有三个角色:observer,event_handler,被监控的文件夹。三者原本是独立的,主要通过observer.schedule函数将三者串起来,意思为observer不断检测调用平台依赖代码对监控文件夹进行变动检测,当发现改变时,通知event_handler处理。最后特别推荐读者有时间可以阅读一下watchdog的源码,写的易懂而且架构很好。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
122 在
学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..123 在
Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..原梓番博客 在
在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..博主 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..1111 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号