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

相关文章

PyTorch快速搭建神经网络及其保存提取方法详解

PyTorch快速搭建神经网络及其保存提取方法详解

有时候我们训练了一个模型, 希望保存它下次直接使用,不需要下次再花时间去训练 ,本节我们来讲解一下PyTorch快速搭建神经网络及其保存提取方法详解 一、PyTorch快速搭建神经网络...

Python比较配置文件的方法实例详解

工作中最常见的配置文件有四种:普通key=value的配置文件、Json格式的配置文件、HTML格式的配置文件以及YMAML配置文件。 这其中以第一种居多,后三种在成熟的开源产品中较为...

点球小游戏python脚本

本文实例为大家分享了python点球小游戏的具体代码,供大家参考,具体内容如下 1.游戏要求: 设置球的方向:左中右三个方向,射门或者扑救动作,循环5次,直接输入方向。电脑随机挑选方...

python字典多键值及重复键值的使用方法(详解)

python字典多键值及重复键值的使用方法(详解)

在Python中使用字典,格式如下: dict={ key1:value1 , key2;value2 ...} 在实际访问字典值时的使用格式如下: dict[key] 多...

python调用Matplotlib绘制分布点并且添加标签

python调用Matplotlib绘制分布点并且添加标签

本文实例为大家分享了Python调用Matplotlib绘制分布点添加标签的具体代码,供大家参考,具体内容如下 添加标签的目的 代码 截图 目的 上文介绍了根据图像...