使用pyinotify监控文件系统变化

匿名 (未验证) 提交于 2019-12-03 00:06:01

pyinotify模块安装

  • pyinotify 是一个python的第三方模块,依赖于linux内核inotify功能
  • 使用pip直接下载:pip install pyinotify

简单的监控文件的实现

import pyinotify wm = pyinotify.WatchManager()                          #创建一个WachManager对象 mask  = pyinotify.IN_CREATE | pyinotify.IN_DELETE      #创建要监控的事件,这里是监控创建文件与删除文件事件 wm.add_watch('要监控的文件路径'mask)  notifier = pyinotify.Notifier(wm)                      #创建一个notifile对象,并将WatchManager对象作为参数传递给Notifile对象 notifier.loop()                                        #调用notifile.loop循环处理事件 

常见的pyinotify提供的事件

事件标志 事件含义
IN_ACCESS 被监控目录有条目被访问
IN_OPEN 文件或目录被打开
IN_DELETE 有目录或文件被删除
IN_CREATE 有文件或目录被创建
ALL_EVENTS 监控所有事件

在实际生产环境中,需要制定事件的处理方式来事件特殊的功能,制定特殊的处理方式的方法为:继承ProcessEvent类,如:

import pyinotify wm = pyinotify.WatchManager()                        mask  = pyinotify.IN_CREATE | pyinotify.IN_DELETE      class Eventhandle(pyinotify.ProcessEvent):          #创建一个类 	def process_IN_CREATE(self,event): 		print("creating: ",event.pathname) 	def process_IN_DELETE(self,event): 		print("removing: ",event.pathname) handle = Eventhandle()                              #实例化 		 wm.add_watch('要监控的文件路径'mask)  notifier = pyinotify.Notifier(wm,handle)                  notifier.loop()                                       
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!