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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM