使用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中pop和remove的使用方法

Python关于删除list中的某个元素,一般有两种方法,pop()和remove()。 remove() 函数用于移除列表中某个值的第一个匹配项。 remove()方法语法: list...

Python实现将照片变成卡通图片的方法【基于opencv】

本文实例讲述了Python实现将照片变成卡通图片的方法。分享给大家供大家参考,具体如下: 之前的文章介绍了使用Photoshop将照片变成卡通图片,今次介绍用代码来实现这项任务,可以就此...

python判断windows隐藏文件的方法

python判断windows隐藏文件的方法

1. 通过windows attrib 命令获取文件隐藏属性复制代码 代码如下:Syntax      ATTRIB [ + attri...

Python笔记之工厂模式

工厂模式: “工厂”即表示一个负责创建其他类型的对象的类,通常情况下,一个工厂的对象会有一个或多个方法与之关联,这些方法用于创建不同类型的对象,工厂对象会根据客户端给方法传递的不同的参数...

python requests 库请求带有文件参数的接口实例

python requests 库请求带有文件参数的接口实例

有些接口参数是一个文件格式,比如fiddler 抓包参数如下显示 这个接口的 form-data fiddler 显示的和不带文件参数的接口有明显区别,显示的不是简单的键值对,所以我们...