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