Python持續(xù)監(jiān)聽(tīng)文件變化代碼實(shí)例
在日常的工作中,有時(shí)候會(huì)有這樣的需求,需要一個(gè)常駐任務(wù),持續(xù)的監(jiān)聽(tīng)一個(gè)目錄下文件的變化,對(duì)此作出回應(yīng).
pyinotify就是這樣的一個(gè)python包,使用方式如下:
一旦src.txt有新的內(nèi)容,程序就可以監(jiān)控到,然后將內(nèi)容發(fā)送
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): # 當(dāng)文件被修改時(shí)調(diào)用函數(shù) 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()
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. APP啟動(dòng)慢怎么辦,Android官方這樣說(shuō)2. Vue實(shí)現(xiàn)div滾輪放大縮小3. Android中的緩存4. Android實(shí)現(xiàn)動(dòng)態(tài)改變shape.xml中圖形的顏色5. PHP擴(kuò)展之APC——Alternative PHP Cache(可選PHP緩存)6. 如何從外部瀏覽開(kāi)啟Android App7. VUE實(shí)時(shí)監(jiān)聽(tīng)元素距離頂部高度的操作8. 解決Android Studio日志太長(zhǎng)或滾動(dòng)太快問(wèn)題9. vue+element-ui JYAdmin后臺(tái)管理系統(tǒng)模板解析10. android RecycleView實(shí)現(xiàn)多級(jí)樹(shù)形列表
