使用Python监控文件内容变化代码实例
利用seek监控文件内容,并打印出变化内容:
#/usr/bin/envpython
#-*-coding=utf-8-*-
pos=0
whileTrue:
con=open("a.txt")
ifpos!=0:
con.seek(pos,0)
whileTrue:
line=con.readline()
ifline.strip():
printline.strip()
pos=pos+len(line)
ifnotline.strip():
break
con.close()
利用工具pyinotify监控文件内容变化,当文件逐渐变大时,可轻松完成任务:
#!/usr/bin/envpython
#-*-coding=utf-8-*-
importos
importdatetime
importpyinotify
importlogging
pos=0
defprintlog():
globalpos
try:
fd=open("log/a.txt")
ifpos!=0:
fd.seek(pos,0)
whileTrue:
line=fd.readline()
ifline.strip():
printline.strip()
pos=pos+len(line)
ifnotline.strip():
break
fd.close()
exceptException,e:
printstr(e)
classMyEventHandler(pyinotify.ProcessEvent):
defprocess_IN_MODIFY(self,event):
try:
printlog()
exceptException,e:
printstr(e)
defmain():
printlog()
wm=pyinotify.WatchManager()
wm.add_watch("log/a.txt",pyinotify.ALL_EVENTS,rec=True)
eh=MyEventHandler()
notifier=pyinotify.Notifier(wm,eh)
notifier.loop()
if__name__=="__main__":
main()