Python监控文件变化:watchdog
2017-11-16 10:05
441 查看
Python监控文件变化有两种库:pyinotify和watchdog。pyinotify依赖于Linux平台的inotify,后者则对不同平台的的事件都进行了封装。也就是说,watchdog跨平台。
下面看一个小demo
watchdog主要采用观察者模型(废话,从变量命名就可以看出来)。主要有三个角色:observer,event_handler,被监控的文件夹。三者原本是独立的,主要通过observer.schedule函数将三者串起来,意思为observer不断检测调用平台依赖代码对监控文件夹进行变动检测,当发现改变时,通知event_handler处理。最后特别推荐读者有时间可以阅读一下watchdog的源码,写的易懂而且架构很好。
watchdog官方文档
参考资料
下面看一个小demo
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 {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的源码,写的易懂而且架构很好。
watchdog官方文档
参考资料
相关文章推荐
- python中文件变化监控-watchdog
- Python监控文件变化:watchdog
- python中文件变化监控示例(watchdog)
- 使用Python监控文件内容变化代码实例
- python 监控文件变化
- Python监控Windows下的文件变化
- python 监控文件变化
- 【Python】监控文件内容增删改操作变化
- python监控文件或目录变化
- python监控文件或目录变化
- Python监控Windows下的文件变化
- Python Watchdog 实行对文件或目录的监控
- python watchdog:监控文件系统事件的Python库
- Python for Windows——监控Windows某个目录下文件的变化
- Python监控目录和文件变化
- python watchdog:监控文件系统事件的Python库
- 监控文件的watchdog
- django 调试 监控文件变化 自动刷新浏览器
- Python pyinotify文件系统监控
- java 实现监控某目录文件变化