Python之pyinotify模块

pyinotify可以用来监测文件系统的变化,它依赖于Linux内核inotify功能。

[root@Ansible ~]# python -m pyinotify /tmp/
<Event dir=True mask=0x40000020 maskname=IN_OPEN|IN_ISDIR name='' path=/tmp pathname=/tmp wd=1 >
<Event dir=True mask=0x40000010 maskname=IN_CLOSE_NOWRITE|IN_ISDIR name='' path=/tmp pathname=/tmp wd=1 >
<Event dir=True mask=0x40000020 maskname=IN_OPEN|IN_ISDIR name='' path=/tmp pathname=/tmp wd=1 >
<Event dir=True mask=0x40000010 maskname=IN_CLOSE_NOWRITE|IN_ISDIR name='' path=/tmp pathname=/tmp wd=1 >
<Event dir=False mask=0x100 maskname=IN_CREATE name=1.txt path=/tmp pathname=/tmp/1.txt wd=1 >
<Event dir=False mask=0x20 maskname=IN_OPEN name=1.txt path=/tmp pathname=/tmp/1.txt wd=1 >
<Event dir=False mask=0x4 maskname=IN_ATTRIB name=1.txt path=/tmp pathname=/tmp/1.txt wd=1 >
<Event dir=False mask=0x8 maskname=IN_CLOSE_WRITE name=1.txt path=/tmp pathname=/tmp/1.txt wd=1 >

1.pyinotify模块的API

Notifier是pyinotify的一个重要的类,用来读取通知和处理事件。Notifier类的初始化函数接受多个参数,但只有WatchManager对象是必传的参数。WatchManager保存了需要监视的文件和目录,以及监视文件的和目录的事件。

import pyinotify
wm = pyinotify.WatchManager()
#所有事件
#mask = pyinotify.ALL_EVENTS
#创建与删除事件
mask = pyinotify.IN_DELETE | pyinotify.IN_CREATE
wm.add_watch('/root',mask)
notifier = pyinotify.Notifier(wm)
notifier.loop()

可以定义一个事件处理类,自定义事件的提醒。

import pyinotify

wm = pyinotify.WatchManager()
mask = pyinotify.IN_DELETE | pyinotify.IN_CREATE

class EventHandler(pyinotify,ProcessEvent):
    def process_IN_CREATE(self,event):
        print("Creating:",event.pathname)
    def process_IN_DELETE(self,event):
        print("Deleting:",event.pathname)
           
handler = EventHandler()
notifier = pyinotify.Notifier(wm,hander)
wdd = wm.add_watch('/root',mask,rec=True)

notifier.loop()


「 文章如果对你有帮助,请点个赞哦^^ 」 

0