网络编程
位置:首页>> 网络编程>> Python编程>> Python持续监听文件变化代码实例

Python持续监听文件变化代码实例

作者:Mars.wang  发布时间:2021-10-20 06:19:19 

标签:python,监听,文件

在日常的工作中,有时候会有这样的需求,需要一个常驻任务,持续的监听一个目录下文件的变化,对此作出回应.

pyinotify就是这样的一个python包,使用方式如下:

一旦src.txt有新的内容,程序就可以监控到,然后将内容发送


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

来源:https://www.cnblogs.com/wangbin2188/p/13334472.html

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com