推薦日志處理項目: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