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

相关文章

PyQt5每天必学之创建窗口居中效果

PyQt5每天必学之创建窗口居中效果

本文实例为大家分享了PyQt5如何能够创建在桌面屏幕上居中窗口的具体代码,供大家参考,具体内容如下 下面的脚本说明我们如何能够创建在桌面屏幕上居中的窗口。 #!/usr/bin/py...

Scrapy框架使用的基本知识

scrapy是一个基于Twisted的异步处理框架,可扩展性很强。优点此处不再一一赘述。 下面介绍一些概念性知识,帮助大家理解scrapy。 一、数据流向 要想熟练掌握这个框架,一定要明...

python3.x 生成3维随机数组实例

python3.x 生成3维随机数组实例

如下所示: import numpy as np a=np.random.randint(0,10,size=[3,3,3]) print(a) 以上这篇python...

pymysql模块的操作实例

pymysql 模块! pymysql模块时一个第三方模块!需要下载: pymysql的基本使用: import pymysql conn = pymysql.connect(...

Python3.5装饰器典型案例分析

本文实例讲述了Python3.5装饰器。分享给大家供大家参考,具体如下: #!/usr/bin/env python # -*- coding:utf-8 -*- # Author:...