Python使用pyinotify持续监听文件变化并发送内容

不晚
不晚
发布时间:2026-10-14 | 3人浏览过
原创

本文介绍如何利用Python的pyinotify库实现目录文件的持续监听。通过定义事件处理类捕获文件修改事件,结合Socket通信将新增内容实时发送至指定服务器。代码示例展示了从文件读取、网络发送到循环监听的完整流程,适用于需要实时响应文件变更的后台常驻任务场景。

Python文件监控需求与pyinotify简介

在实际开发工作中,经常需要运行一个常驻进程,持续监控指定目录下的文件变动,并对这些变动做出即时响应。

pyinotify是一个Python包,专门用于处理此类文件监控需求,其基本使用方法如下所示。

当源文件src.txt产生新内容时,程序能够检测到该变化,并将读取到的内容通过通信接口发送出去。

文件监听与Socket通信代码实现


import socket
import pyinotify
pos = 0


def send(c):
  c_list = [c]
  s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  s.connect(('127.0.0.1', 10001))
  print(s.recv(1024).decode('utf-8'))
  for data in c_list:
    s.send(data)
    print(s.recv(1024).decode('utf-8'))
  s.send(b'exit')
  s.close()


def printlog():
  global pos
  try:
    fd = open("src.txt")
    if pos != 0:
      fd.seek(pos, 0)
    while True:
      line = fd.readline()
      if line.strip():
        send(line.strip().encode('utf8'))
      pos = pos + len(line)
      if not line.strip():
        break
    fd.close()
  except Exception as e:
    print(str(e))


class MyEventHandler(pyinotify.ProcessEvent):

  # 当文件被修改时调用函数
  def process_IN_MODIFY(self, event):
    try:
      printlog()
    except Exception as e:
      print(str(e))
if __name__ == '__main__':
  printlog()
  # watch manager
  wm = pyinotify.WatchManager()
  wm.add_watch('/home/ubuntu/data-sync/s3', pyinotify.ALL_EVENTS, rec=True)
  eh = MyEventHandler()

  # notifier
  notifier = pyinotify.Notifier(wm, eh)
  notifier.loop()

以上即为本文介绍的核心内容,希望能为读者的学习提供有益参考,同时也欢迎大家继续支持本站。

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表