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

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

#/usr/bin/env python
#-*- coding=utf-8 -*-
 
pos = 0
while 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监控文件内容变化,当文件逐渐变大时,可轻松完成任务:

#!/usr/bin/env python
#-*- coding=utf-8 -*-
import os
import datetime
import pyinotify
import logging
 
pos = 0
def 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()

声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。