使用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 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM