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

yipeiwu_com5年前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()

相关文章

pip install urllib2不能安装的解决方法

python35 urllib2 不能用 Could not find a version that satisfies the requirement urllib2 (from...

Python+matplotlib实现华丽的文本框演示代码

Python+matplotlib实现华丽的文本框演示代码

华丽的文本框演示 首先看看演示结果: 实现代码 import matplotlib.pyplot as plt plt.text(0.8, 0.5, "python", size...

python socket网络编程之粘包问题详解

python socket网络编程之粘包问题详解

一,粘包问题详情 1,只有TCP有粘包现象,UDP永远不会粘包 你的程序实际上无权直接操作网卡的,你操作网卡都是通过操作系统给用户程序暴露出来的接口,那每次你的程序要给远程发数据时,...

详解Python的Django框架中Manager方法的使用

在语句Book.objects.all()中,objects是一个特殊的属性,需要通过它查询数据库。 在第5章,我们只是简要地说这是模块的manager 。现在是时候深入了解manage...

Python简单实现TCP包发送十六进制数据的方法

本文实例讲述了Python简单实现TCP包发送十六进制数据的方法。分享给大家供大家参考,具体如下: 举例: 0x12, 0x34可以直接拼成 "\x12\x34"。 客户端代码示例:...