Python实现文件内容实时监控的两种方案:Seek与Pyinotify

阿麦
阿麦
发布时间:2026-10-13 | 1人浏览过
原创

本文介绍两种在Python中监控文件内容变化的方法。第一种利用文件对象的seek方法定位偏移量,适用于简单的轮询场景;第二种借助pyinotify库监听文件系统事件,当文件增大时自动读取新增内容。文中提供了完整的代码示例,帮助开发者实现日志或数据文件的实时追踪与打印输出。

通过利用文件对象的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 相关产品和应用

全部下载

专题列表