使用pyinotify监控文件系统的变化

    pyinotify依赖Linux内核inotify功能,它需要在2.6.13版本的内核的Linux系统上运行。

1. 安装pyinotify

pip install pyinotify

安装完后可以直接在命令行上运行

python -m pyinotify /tmp

2. 使用Notifier

  Notifiter是pyinotify模块最重要的类,用来读取通知和处理事件,其中WatchManage对象是必传的参数,

WatchManager保存了需要监视的文件和目录,以及监视哪些事件。

 3. 事件处理器

   定制事件处理方式的方法是继承ProcessEvent类,并实现process_EVNET_NAME方法

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("Removing:", event.pathname)

handler = EventHandler()
notifier = pyinotify.Notifier(wm, handler)
wdd = wm.add_watch('/tmp', mask, rec=True)

notifier.loop()

 

利用pyinotify可以做很多有趣的事情:参考一个有趣的命令行工具:https://github.com/copton/react 

原文地址:https://www.cnblogs.com/zydev/p/8734752.html