Python文件监听工具pyinotify与watchdog实例
pyinotify库
支持的监控事件
@cvarIN_ACCESS:Filewasaccessed. @typeIN_ACCESS:int @cvarIN_MODIFY:Filewasmodified. @typeIN_MODIFY:int @cvarIN_ATTRIB:Metadatachanged. @typeIN_ATTRIB:int @cvarIN_CLOSE_WRITE:Writtablefilewasclosed. @typeIN_CLOSE_WRITE:int @cvarIN_CLOSE_NOWRITE:Unwrittablefileclosed. @typeIN_CLOSE_NOWRITE:int @cvarIN_OPEN:Filewasopened. @typeIN_OPEN:int @cvarIN_MOVED_FROM:FilewasmovedfromX. @typeIN_MOVED_FROM:int @cvarIN_MOVED_TO:FilewasmovedtoY. @typeIN_MOVED_TO:int @cvarIN_CREATE:Subfilewascreated. @typeIN_CREATE:int @cvarIN_DELETE:Subfilewasdeleted. @typeIN_DELETE:int @cvarIN_DELETE_SELF:Self(watcheditemitself)wasdeleted. @typeIN_DELETE_SELF:int @cvarIN_MOVE_SELF:Self(watcheditemitself)wasmoved. @typeIN_MOVE_SELF:int @cvarIN_UNMOUNT:Backingfswasunmounted. @typeIN_UNMOUNT:int @cvarIN_Q_OVERFLOW:Eventqueuedoverflowed. @typeIN_Q_OVERFLOW:int @cvarIN_IGNORED:Filewasignored. @typeIN_IGNORED:int @cvarIN_ONLYDIR:onlywatchthepathifitisadirectory(new inkernel2.6.15). @typeIN_ONLYDIR:int @cvarIN_DONT_FOLLOW:don'tfollowasymlink(newinkernel2.6.15). IN_ONLYDIRwecanmakesurethatwedon'twatch thetargetofsymlinks. @typeIN_DONT_FOLLOW:int @cvarIN_EXCL_UNLINK:Eventsarenotgeneratedforchildrenafterthey havebeenunlinkedfromthewatcheddirectory. (newinkernel2.6.36). @typeIN_EXCL_UNLINK:int @cvarIN_MASK_ADD:addtothemaskofanalreadyexistingwatch(new inkernel2.6.14). @typeIN_MASK_ADD:int @cvarIN_ISDIR:Eventoccurredagainstdir. @typeIN_ISDIR:int @cvarIN_ONESHOT:Onlysendeventonce. @typeIN_ONESHOT:int @cvarALL_EVENTS:Aliasforconsideringalloftheevents. @typeALL_EVENTS:int
python3.6的demo
importsys importos importpyinotify WATCH_PATH='/home/lp/ftp'#监控目录 ifnotWATCH_PATH: print("TheWATCH_PATHsettingMUSTbeset.") sys.exit() else: ifos.path.exists(WATCH_PATH): print('Foundwatchpath:path=%s.'%(WATCH_PATH)) else: print('ThewatchpathNOTexists,watchingstopnow:path=%s.'%(WATCH_PATH)) sys.exit() #事件回调函数 classOnIOHandler(pyinotify.ProcessEvent): #重写文件写入完成函数 defprocess_IN_CLOSE_WRITE(self,event): #logging.info("createfile:%s"%os.path.join(event.path,event.name)) #处理成小图片,然后发送给grpc服务器或者发给kafka file_path=os.path.join(event.path,event.name) print('文件完成写入',file_path) #重写文件删除函数 defprocess_IN_DELETE(self,event): print("文件删除:%s"%os.path.join(event.path,event.name)) #重写文件改变函数 defprocess_IN_MODIFY(self,event): print("文件改变:%s"%os.path.join(event.path,event.name)) #重写文件创建函数 defprocess_IN_CREATE(self,event): print("文件创建:%s"%os.path.join(event.path,event.name)) defauto_compile(path='.'): wm=pyinotify.WatchManager() #mask=pyinotify.EventsCodes.ALL_FLAGS.get('IN_CREATE',0) #mask=pyinotify.EventsCodes.FLAG_COLLECTIONS['OP_FLAGS']['IN_CREATE']#监控内容,只监听文件被完成写入 mask=pyinotify.IN_CREATE|pyinotify.IN_CLOSE_WRITE notifier=pyinotify.ThreadedNotifier(wm,OnIOHandler())#回调函数 notifier.start() wm.add_watch(path,mask,rec=True,auto_add=True) print('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) print('monitorclose')
watchdog库
支持的监控事件
EVENT_TYPE_MODIFIED:self.on_modified, EVENT_TYPE_MOVED:self.on_moved, EVENT_TYPE_CREATED:self.on_created, EVENT_TYPE_DELETED:self.on_deleted,
需要注意的是,文件改变,也会触发文件夹的改变
python3.6的demo
#!/usr/bin/envpython #-*-coding:utf-8-*- from__future__importprint_function importasyncio importbase64 importlogging importos importshutil importsys fromdatetimeimportdatetime fromwatchdog.eventsimportFileSystemEventHandler fromwatchdog.observersimportObserver WATCH_PATH='/home/lp/ftp'#监控目录 classFileMonitorHandler(FileSystemEventHandler): def__init__(self,**kwargs): super(FileMonitorHandler,self).__init__(**kwargs) #监控目录目录下面以device_id为目录存放各自的图片 self._watch_path=WATCH_PATH #重写文件改变函数,文件改变都会触发文件夹变化 defon_modified(self,event): ifnotevent.is_directory:#文件改变都会触发文件夹变化 file_path=event.src_path print("文件改变:%s"%file_path) if__name__=="__main__": event_handler=FileMonitorHandler() observer=Observer() observer.schedule(event_handler,path=WATCH_PATH,recursive=True)#recursive递归的 observer.start() observer.join()
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对毛票票的支持。如果你想了解更多相关内容请查看下面相关链接