更多编程教程请到:菜鸟教程 https://www.piaodoo.com/
友情链接:好看站 http://www.nrso.net/
高州阳光论坛https://www.hnthzk.com/在日常的工作中,有时候会有这样的需求,需要一个常驻任务,持续的监听一个目录下文件的变化,对此作出回应.
pyinotify就是这样的一个python包,使用方式如下:
一旦src.txt有新的内容,程序就可以监控到,然后将内容发送
import socket import pyinotify pos = 0
def send©:
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()
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持菜鸟教程www.piaodoo.com。