python监视文件变化,pyinotify模块监控文件与文件夹变化

发布时间:2019-12-06编辑:脚本学堂
python pyinotify模块的例子,通过pyinotify模块进程文件/文件夹的监视,监控文件内容的变化,文件属性的修改等信息。

通过pyinotify模块进程文件/文件夹的监视,如果还需要监视其他内容,比如修改等,可以查看help(pyinotify).

代码:
 

复制代码 代码示例:

#!/usr/bin/env python
#coding=utf-8
# www.jb200.com

import os
import gobject
from  pyinotify import  WatchManager, Notifier, ProcessEvent, ThreadedNotifier, IN_DELETE, IN_CREATE,IN_MOVED_TO,IN_MOVED_FROM
 
class MonitorFile(ProcessEvent): 
def process_IN_CREATE(self, event):
print   " CREATE: %s "  %   os.path.join(event.path, event.name)

def process_IN_DELETE(self, event):
print   " DELETE: %s "  %   os.path.join(event.path, event.name)

def process_IN_MOVED_TO(self, event):
print   " MOVED_TO: %s "  %   os.path.join(event.path, event.name)

def process_IN_MOVED_FROM(self, event):
print   " MOVED_FROM: %s "  %   os.path.join(event.path, event.name)

path = "/usr/local/etc/"
gobject.threads_init()
wm = WatchManager()
mask = IN_DELETE|IN_CREATE|IN_MOVED_TO|IN_MOVED_FROM
notifier = ThreadedNotifier(wm, MonitorFile ())
wm.add_watch(path, mask,rec=True)
notifier.start()
 
if __name__ == "__main__":

try:
while True:
pass
except Exception,e:
 print str(e)
 notifier.stop()

问题:
之前可以监视文件,现在只能监视文件夹,待查。