使用Python監(jiān)控文件內(nèi)容變化代碼實(shí)例
利用seek監(jiān)控文件內(nèi)容,并打印出變化內(nèi)容:
#/usr/bin/env python #-*- coding=utf-8 -*- pos = 0 while True: con = open("a.txt") if pos != 0: con.seek(pos,0) while True: line = con.readline() if line.strip(): print line.strip() pos = pos + len(line) if not line.strip(): break con.close()
利用工具pyinotify監(jiān)控文件內(nèi)容變化,當(dāng)文件逐漸變大時(shí),可輕松完成任務(wù):
#!/usr/bin/env python #-*- coding=utf-8 -*- import os import datetime import pyinotify import logging pos = 0 def printlog(): global pos try: fd = open("log/a.txt") if pos != 0: fd.seek(pos,0) while True: line = fd.readline() if line.strip(): print line.strip() pos = pos + len(line) if not line.strip(): break fd.close() except Exception,e: print str(e) class MyEventHandler(pyinotify.ProcessEvent): def process_IN_MODIFY(self,event): try: printlog() except Exception,e: print str(e) def main(): printlog() wm = pyinotify.WatchManager() wm.add_watch("log/a.txt",pyinotify.ALL_EVENTS,rec=True) eh = MyEventHandler() notifier = pyinotify.Notifier(wm,eh) notifier.loop() if __name__ == "__main__": main()
相關(guān)文章
使用Python對(duì)MySQL數(shù)據(jù)操作
本文介紹Python3使用PyMySQL連接數(shù)據(jù)庫(kù),并實(shí)現(xiàn)簡(jiǎn)單的增刪改查。具有很好的參考價(jià)值。下面跟著小編一起來(lái)看下吧2017-04-04使用Python給PDF添加目錄書(shū)簽的實(shí)現(xiàn)方法
有時(shí)下載到掃描版的 PDF 是不帶書(shū)簽?zāi)夸浀?這樣閱讀起來(lái)很不方便,下面通過(guò) python 實(shí)現(xiàn)一個(gè)半自動(dòng)化添加書(shū)簽?zāi)夸浀哪_本,文中通過(guò)代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,需要的朋友可以參考下2023-10-10django自定義非主鍵自增字段類(lèi)型詳解(auto increment field)
這篇文章主要介紹了django自定義非主鍵自增字段類(lèi)型詳解(auto increment field),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-03-03對(duì)Tensorflow中的變量初始化函數(shù)詳解
今天小編就為大家分享一篇對(duì)Tensorflow中的變量初始化函數(shù)詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-07-07教你用Type Hint提高Python程序開(kāi)發(fā)效率
本文通過(guò)介紹和實(shí)例教大家如何利用Type Hint來(lái)提升Python程序開(kāi)發(fā)效率,對(duì)大家使用python開(kāi)發(fā)很有幫助,有需要的參考學(xué)習(xí)。2016-08-08Django項(xiàng)目在pycharm新建的步驟方法
在本篇文章里小編給大家整理的是一篇關(guān)于Django項(xiàng)目在pycharm新建的步驟方法,有興趣的朋友們可以學(xué)習(xí)參考下。2021-03-03pytorch訓(xùn)練imagenet分類(lèi)的方法
今天小編就為大家分享一篇pytorch訓(xùn)練imagenet分類(lèi)的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-07-07