使用Python監(jiān)控文件內(nèi)容變化代碼實例
更新時間:2018年06月04日 08:52:57 作者:guoswcfl
在python中文件監(jiān)控主要有兩個庫,一個是pyinotify,一個是watchdog。pyinotify依賴于Linux平臺的inotify,今天我們就來探討下pyinotify.
利用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)容變化,當文件逐漸變大時,可輕松完成任務:
#!/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()
相關文章
django自定義非主鍵自增字段類型詳解(auto increment field)
這篇文章主要介紹了django自定義非主鍵自增字段類型詳解(auto increment field),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-03-03教你用Type Hint提高Python程序開發(fā)效率
本文通過介紹和實例教大家如何利用Type Hint來提升Python程序開發(fā)效率,對大家使用python開發(fā)很有幫助,有需要的參考學習。2016-08-08