環境要求
- Linux >= 2.6.13
- Python ≥ 2.4 (including Python 3.x)
pyinotify
檢測檔案系統的變化,依賴于Linux核心的inotify功能。
1.安裝
pip install pyinotify
2.簡單使用
import pyinotify
monitorObj = pyinotify.WatchManager()
monitorObj.add_watch(path,pyinotify.ALL_EVENTS, rec=True, auto_add=True) # 添加需要監控的路徑和監控的事件
handler = EventHandler() # 事件處理類
notifier = pyinotify.Notifier(monitorObj, handler) # notifier處理
notifier.loop() # 循環處理事件
3.事件處理
在簡單使用中的EventHandler類需要我們進行定制,實作對事件的特殊處理方法
import pyinotify
multi_event = pyinotify.IN_OPEN | pyinotify.IN_CLOSE_NOWRITE
monitorObj = pyinotify.WatchManager()
class MyEventHandler(pyinotify.ProcessEvent):
def process_IN_OPEN(self,event):
print('OPEN',event.pathname)
def process_IN_CLOSE_NOWRITE(self,event):
print('CLOSE_NOWRITE',event.pathname)
handler = MyEventHandler()
notifier = pyinotify.Notifier(monitorObj ,handler)
monitorObj.add_watch(path,multi_event)
notifier.loop()
4.事件标志
以下事件發生的前提都是相關檔案處于被監控目錄下
事件标志 | 含義 | 其他 |
---|---|---|
IN_ACCESS | 檔案被通路 | |
IN_ATTRIB | 檔案的一個中繼資料發生變化 | 包括權限改變,時間戳,擴充屬性被修改,連結數變化,所屬使用者/使用者組變化等等 |
IN_CLOSE_NOWRITE | 一個不可寫檔案被關閉 | |
IN_CLOSE_WRITE | 一個可寫檔案被關閉 | |
IN_CREATE | 一個檔案或目錄被建立 | |
IN_DELETE | 一個檔案或目錄被删除 | |
IN_DELETE_SELF | 被監視的對象本身被删除 | |
IN_DONT_FOLLOW | 如果是符号連結,則不取消引用路徑 | |
IN_IGNORED | 當watch被移除時發生 | 使用者一般用不到,可用IN_DELETE* 代替 |
IN_ISDIR | 和目錄引發的事件有關 | |
IN_MASK_ADD | 更新mask值并不覆寫原值 | |
IN_MODIFY | 一個檔案被修改 | |
IN_MOVE_SELF | 被監控的對象本身被移動了 | |
IN_MOVED_FROM | 被監控路徑中的一個檔案/目錄從另一個被監控的路徑移動而來 | |
IN_MOVED_TO | 被監控路徑中的一個檔案/目錄移動到另一個被監控的路徑 | |
IN_ONLYDIR | 隻監控路徑如果它隻是個目錄 | |
IN_OPEN | 一個檔案被打開 | |
IN_Q_OVERFLOW | 事件隊列溢出 | |
IN_UNMOUNT | when backing fs was unmounted |
參考資料
https://github.com/seb-m/pyinotify/wik