zoukankan      html  css  js  c++  java
  • 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()
  • 相关阅读:
    用 Web 实现一个简易的音频编辑器
    TypeScript教程
    他的独,殇情沉醉
    重新拎一遍js的正则表达式
    网络流
    Xmind最新的安装与破解教程
    adb的端口号5037被占用的解决方法
    使用Fiddler模拟弱网测试教程
    web的前台、后台、前端、后端
    常见面试笔试题
  • 原文地址:https://www.cnblogs.com/wangbin2188/p/13334472.html
Copyright © 2011-2022 走看看