基礎概念
inotify 是取用 linux 底下的系統自動監聽檔案變化的方式,
pyinotify 就是他的 python 版本實作,
當我們獲得了系統給的 event,我們會得到該檔案的「絕對路徑」,
我們就能再進一步依照此絕對路徑做對應的資料操作。
注意:inotify的功能目前只在 linux 系統能使用,mac 上不能使用哦~ (自己親自測試過QQ)
使用範例
pyinotify 做到的效果就是:如果當某個資料夾底下有資料變化,
舉一些例子例如:
– 新增:process_IN_CREATE
– 修改:process_IN_MODIFY
– 刪除:process_IN_DELETE
– 資料被開啟:process_IN_OPEN
– 資料屬性變化:process_IN_ATTRIB (可搭配touch使用,獲得目標檔案路徑)
Sample Code
import pyinotify
class MyEventHandler(pyinotify.ProcessEvent):
def process_IN_ACCESS(self, event):
print("ACCESS event:", event.pathname)
def process_IN_ATTRIB(self, event):
print("ATTRIB event:", event.pathname)
def process_IN_CLOSE_NOWRITE(self, event):
print("CLOSE_NOWRITE event:", event.pathname)
def process_IN_CLOSE_WRITE(self, event):
print("CLOSE_WRITE event:", event.pathname)
def process_IN_CREATE(self, event):
print("CREATE event:", event.pathname)
def process_IN_DELETE(self, event):
print("DELETE event:", event.pathname)
def process_IN_MODIFY(self, event):
print("MODIFY event:", event.pathname)
def process_IN_OPEN(self, event):
print("OPEN event:", event.pathname)
if __name__ == '__main__':
# To specify two or more events codes just orize them
# pyinotify_flags = pyinotify.IN_CREATE | pyinotify.IN_DELETE | pyinotify.IN_MODIFY
# Or if you want to be notified for all events just use this shortcut
pyinotify_flags = pyinotify.ALL_EVENTS
# watch manager
wm = pyinotify.WatchManager()
watch_path = '/home/ubuntu/Desktop/'
wm.add_watch(watch_path, pyinotify_flags, rec=True) # rec = recursive
# event handler
eh = MyEventHandler()
# notifier
notifier = pyinotify.Notifier(wm, eh)
notifier.loop()