Python中使用Inotify监控文件实例
Inotify地址:访问
#-*-coding:utf-8-*- importos importpyinotify fromfunctionsimport* WATCH_PATH=''#监控目录 ifnotWATCH_PATH: wlog('Error',"TheWATCH_PATHsettingMUSTbeset.") sys.exit() else: ifos.path.exists(WATCH_PATH): wlog('Watchstatus','Foundwatchpath:path=%s.'%(WATCH_PATH)) else: wlog('Error','ThewatchpathNOTexists,watchingstopnow:path=%s.'%(WATCH_PATH)) sys.exit() classOnIOHandler(pyinotify.ProcessEvent): defprocess_IN_CREATE(self,event): wlog('Action',"createfile:%s"%os.path.join(event.path,event.name)) defprocess_IN_DELETE(self,event): wlog('Action',"deletefile:%s"%os.path.join(event.path,event.name)) defprocess_IN_MODIFY(self,event): wlog('Action',"modifyfile:%s"%os.path.join(event.path,event.name)) defauto_compile(path='.'): wm=pyinotify.WatchManager() mask=pyinotify.IN_CREATE|pyinotify.IN_DELETE|pyinotify.IN_MODIFY notifier=pyinotify.ThreadedNotifier(wm,OnIOHandler()) notifier.start() wm.add_watch(path,mask,rec=True,auto_add=True) wlog('StartWatch','Startmonitoring%s'%path) whileTrue: try: notifier.process_events() ifnotifier.check_events(): notifier.read_events() exceptKeyboardInterrupt: notifier.stop() break if__name__=="__main__": auto_compile(WATCH_PATH)