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()
来源:51CTO
作者:萌贱
链接:https://blog.csdn.net/yyh0507/article/details/100847832