python 實時遍歷日志文件


推薦日志處理項目:https://github.com/olajowon/loggrove

 

首先嘗試使用 python open 遍歷一個大日志文件,

使用 readlines() 還是 readline() ?

總體上 readlines() 不慢於python 一次次調用 readline(),因為前者的循環在C語言層面,而使用readline() 的循環是在Python語言層面。

但是 readlines() 會一次性把全部數據讀到內存中,內存占用率會過高,readline() 每次只讀一行,對於讀取 大文件, 需要做出取舍。

如果不需要使用 seek() 定位偏移, for line in open('file') 速度更佳。

 

使用 readlines(),適合量級較小的日志文件

復制代碼
 1 p = 0
 2 with open(filepath, 'r+') as f:
 3     f.seek(p, 0)
 4     while True:
 5         lines = f.readlines()
 6         if lines:
 7             print lines
 8             p = f.tell()
 9             f.seek(p, 0)
10         time.sleep(1)
復制代碼

 

使用 readline(),避免內存占用率過大

1 p = 0
2 with open('logs.txt', 'r+') as f:
3     while True:
4         line = f.readline()
5         if line:
6             print line

 

################## 華麗分割 ##########################

現在嘗試使用 tail -F log.txt 動態輸出

由於 os.system() , commands.getstatusoutput() 屬於一次性執行就拜拜, 最終選擇 subprocess.Popen(),

subprocess 模塊目的是啟動一個新的進程並與之通信,最常用是定義類Popen,使用Popen可以創建進程,並與進程進行交互。

復制代碼
1 import subprocess
2 import time
3 
4 p = subprocess.Popen('tail -F log.txt', shell=True, stdout=subprocess.PIPE,stderr=subprocess.PIPE,)
5 while True:
6    line = p.stdout.readline()
7    if line:
8         print line
復制代碼


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM