用pyinotify監控文件系統示例
Pyinotify是一個Python模塊,用來監測文件系統的變化。 Pyinotify依賴于Linux內核的功能—inotify(內核2.6.13合并)。 inotify的是一個事件驅動的通知器,其通知接口通過三個系統調用從內核空間到用戶空間。pyinotify結合這些系統調用,并提供一個頂級的抽象和一個通用的方式來處理這些功能。
pyinotify其實就是通過調用系統的inotify來實現通知的。
1. 安裝
git clone https://github.com/seb-m/pyinotify.git cd pyinotify/ python setup.py install
2. 簡單使用
import os from pyinotify import WatchManager, Notifier, ProcessEvent, IN_DELETE, IN_CREATE, IN_MODIFY class EventHandler(ProcessEvent): def process_IN_CREATE(self, event): print "Create file:%s." %os.path.join(event.path,event.name) os.system('cp -rf %s /tmp/bak/'%(os.path.join(event.path,event.name))) def process_IN_DELETE(self, event): print "Delete file:%s." %os.path.join(event.path,event.name) def process_IN_MODIFY(self, event): print "Modify file:%s." %os.path.join(event.path,event.name) def FsMonitor(path='.'): wm = WatchManager() mask = IN_DELETE | IN_CREATE | IN_MODIFY notifier = Notifier(wm, EventHandler()) wm.add_watch(path, mask, auto_add= True, rec=True) print "now starting monitor %s." %path while True: try: notifier.process_events() if notifier.check_events(): print "check event true." notifier.read_events() except KeyboardInterrupt: print "keyboard Interrupt." notifier.stop() break if __name__ == "__main__": FsMonitor("/root/work/")
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!