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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章