久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁技術文章
文章詳情頁

Python持續監聽文件變化代碼實例

瀏覽:2日期:2022-07-16 15:49:40

在日常的工作中,有時候會有這樣的需求,需要一個常駐任務,持續的監聽一個目錄下文件的變化,對此作出回應.

pyinotify就是這樣的一個python包,使用方式如下:

一旦src.txt有新的內容,程序就可以監控到,然后將內容發送

import socketimport pyinotifypos = 0def 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()

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。

標簽: Python 編程
相關文章:
主站蜘蛛池模板: 运城市| 乳源| 武强县| 柳江县| 昭觉县| 吴桥县| 兴隆县| 兴安盟| 北安市| 武川县| 丰城市| 揭阳市| 大庆市| 星子县| 澎湖县| 龙海市| 徐州市| 嘉定区| 华宁县| 沈丘县| 农安县| 牟定县| 湖口县| 淳化县| 平顶山市| 昭苏县| 白水县| 德钦县| 资中县| 邻水| 仁布县| 顺平县| 古交市| 贵德县| 信宜市| 安福县| 霍邱县| 昭通市| 招远市| 右玉县| 台湾省|