PHP前端开发

使用Python监控文件内容变化代码

百变鹏仔 3小时前 #Python
文章标签 代码

这篇文章主要介绍了关于使用python监控文件内容变化代码,有着一定的参考价值,现在分享给大家,有需要的朋友可以参考一下

在python中文件监控主要有两个库,一个是pyinotify,一个是watchdog。pyinotify依赖于Linux平台的inotify,今天我们就来探讨下pyinotify.

利用seek监控文件内容,并打印出变化内容:

#/usr/bin/env python#-*- coding=utf-8 -*- pos = 0while True:  con = open("a.txt")  if pos != 0:    con.seek(pos,0)  while True:  line = con.readline()  if line.strip():    print line.strip()  pos = pos + len(line)  if not line.strip():    break  con.close()

利用工具pyinotify监控文件内容变化,当文件逐渐变大时,可轻松完成任务:

立即学习“Python免费学习笔记(深入)”;

#!/usr/bin/env python#-*- coding=utf-8 -*-import osimport datetimeimport pyinotifyimport logging pos = 0def printlog():  global pos  try:    fd = open("log/a.txt")  if pos != 0:    fd.seek(pos,0)  while True:    line = fd.readline()    if line.strip():      print line.strip()    pos = pos + len(line)    if not line.strip():    break  fd.close()  except Exception,e:  print str(e) class MyEventHandler(pyinotify.ProcessEvent):  def process_IN_MODIFY(self,event):    try:    printlog()  except Exception,e:    print str(e) def main():  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()