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

 

posted @ 2020-07-18 08:33  Mars.wang  阅读(1213)  评论(0编辑  收藏  举报