#!/usr/bin/env python # -*- coding:utf-8 -*- # Created by victor # 本模块的功能:<检测文件夹变化> # 导入watchdog对应模块 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 = Observer() event_handler = FileEventHandler() # 设置监听目录 dis_dir = "e:/" observer.schedule(event_handler,dis_dir,True) observer.start() try: while True: # 设置监听频率(间隔周期时间) time.sleep(1) except KeyboardInterrupt: observer.stop() observer.join()
小结
watchdog主要采用观察者模型。主要有三个角色:observer,event_handler,被监控的文件夹。三者原本是独立的,主要通过observer.schedule函数将三者串起来,意思为observer不断检测调用平台依赖代码对监控文件夹进行变动检测,当发现改变时,通知event_handler处理。