• 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()
  • 相关阅读:
    点击button先执行js在执行后台代码客户端判断控件是否为空
    VNC远程登录端使用经验之一
    TB平台搭建之一
    能力不足之 根据时序图转化为Verilog代码
    Verilog之语句位置
    verilog 1995 VS 2001 part1模块声明的扩展
    verilog $fopen 函数的小缺陷
    tab key usage
    poj2184 Cow Exhibition
    hdu2546 饭卡
  • 原文地址:https://www.cnblogs.com/wangbin2188/p/13334472.html
Copyright © 2020-2023  润新知