使用Python監(jiān)控文件內(nèi)容變化代碼實(shí)例
更新時(shí)間:2018年06月04日 08:52:57 作者:guoswcfl
在python中文件監(jiān)控主要有兩個(gè)庫,一個(gè)是pyinotify,一個(gè)是watchdog。pyinotify依賴于Linux平臺(tái)的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)容變化,當(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)文章
實(shí)例講解Python爬取網(wǎng)頁數(shù)據(jù)
這篇文章給大家通過實(shí)例講解了Python爬取網(wǎng)頁數(shù)據(jù)的步驟以及操作過程,有興趣的朋友跟著學(xué)習(xí)下吧。2018-07-07
Python實(shí)現(xiàn)關(guān)鍵路徑和七格圖計(jì)算詳解
這篇文章主要為大家詳細(xì)介紹了如何利用Python實(shí)現(xiàn)關(guān)鍵路徑和七格圖計(jì)算,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起了解一下2023-03-03
Django使用HTTP協(xié)議向服務(wù)器傳參方式小結(jié)
本文主要介紹了Django使用HTTP協(xié)議向服務(wù)器傳參方式小結(jié),用戶發(fā)送請(qǐng)求時(shí)攜帶的參數(shù)后端需要使用,而不同的發(fā)送參數(shù)的方式對(duì)應(yīng)了不同的提取參數(shù)的方式,本文就詳細(xì)的介紹一下2021-08-08
解決Python下imread,imwrite不支持中文的問題
今天小編就為大家分享一篇解決Python下imread,imwrite不支持中文的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-12-12
python-opencv 中值濾波{cv2.medianBlur(src, ksize)}的用法
這篇文章主要介紹了python-opencv 中值濾波{cv2.medianBlur(src, ksize)}的用法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。2021-06-06
OpenCV+python實(shí)現(xiàn)膨脹和腐蝕的示例
這篇文章主要介紹了OpenCV+python實(shí)現(xiàn)膨脹和腐蝕的示例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-12-12

