欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-11-24 17:34:22
利用seek监控文件内容,并打印出变化内容: #/usr/bin/env python #-*- coding=utf-8 -*- pos = 0 w...

利用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()