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

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

相关文章

聊聊Python中的pypy

聊聊Python中的pypy

PyPy是一个虚拟机项目,主要分为两部分:一个Python的实现和 一个编译器 PyPy的第一部分: 用Python实现的Python   其实这么说并不准确,准确得说应该是用rPy...

Django框架实现的普通登录案例【使用POST方法】

Django框架实现的普通登录案例【使用POST方法】

本文实例讲述了Django框架实现的普通登录。分享给大家供大家参考,具体如下: 1.显示登录页面 a.设计url,通过浏览器访问http://127.0.0.1:8000//login的...

python机器学习库常用汇总

汇总整理一套Python网页爬虫,文本处理,科学计算,机器学习和数据挖掘的兵器谱。 1. Python网页爬虫工具集 一个真实的项目,一定是从获取数据开始的。无论文本处理,机器学习和数据...

Python Requests库基本用法示例

本文实例讲述了Python Requests库基本用法。分享给大家供大家参考,具体如下: requests是python的一个http client库,提供了一套简捷的API供开发者使用...

Python 实用技巧之利用Shell通配符做字符串匹配

1、需求 当工作在UNIX Shell下时,我们想使用常见的通配符模式(即:.py,Dat[0-9].csv等)来对文本做匹配。 2、解决方案 fnmatch模块提供了两个函数:fnma...