使用pyinotify 检测文件夹内容变化

使用 pyinotify 监测文件夹的内文件的变化,需要两步,安装和代码编写


1.安装

 使用简单的方法 

# easy_install pyinotify

2. 代码编写


from  pyinotify import  WatchManager, Notifier,ProcessEvent,EventsCodes

class EventHandler(ProcessEvent): # 事件处理函数,应与 FSMonitor类的 mask变量一致(设置监听的事件类型)
    """事件处理"""
    def process_IN_CREATE(self, event):

        print   ("Create file: %s "  %   event.path)
#  
#     def process_IN_DELETE(self, event):
#         print  ( "Delete file: %s "  %   event.path)
#  
    def process_IN_MODIFY(self, event):
        print  ( "Modify file: %s "  %   event.path)

 
def FSMonitor(path='/root/xml/'):
        wm = WatchManager()
        mask =EventsCodes.FLAG_COLLECTIONS['OP_FLAGS']['IN_MODIFY'] #|EventsCodes.FLAG_COLLECTIONS['OP_FLAGS']['IN_CREATE'] 设置监听的事件(或操作)
        print('mask==',mask)
        
        notifier = Notifier(wm, EventHandler())
        wm.add_watch(path, mask,rec=True)
        print( 'now starting monitor %s'%(path))
        while True:
                try:
                        notifier.process_events()
                        if notifier.check_events():
                                notifier.read_events()
                except KeyboardInterrupt:
                        notifier.stop()
                        break
 
if __name__ == "__main__":
    FSMonitor()

你可能感兴趣的:(python)