如何从日志fi获取最后值

2024-05-01 21:47:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个日志文件,保存温度值。
使用这个代码,我只能从中提取温度值。在

代码:

import re
import itertools

infile = "/home/pi/Mysensor/Logs/test.log"
for line in open(infile):
    match = re.search('Temp=(\d+)', line)
    if match:
        test = match.group(1)
        print test

我的日志文件:

^{pr2}$

代码输出:

28
28
25
29
28
25

我想做的是,只提取最后四个结果。
我尝试过数组和列表。但没有结果。在

我错过了什么?
如何让这个程序只得到最后四个结果?在

提前谢谢。在


Tags: 文件代码testimportreloghomematch
3条回答

一种简单的方法是使用linuxshell中的tail

  1 import os
  2 
  3 def my_tail(f, n):
  4     stdin, stdout = os.popen2("tail -n " + str(n) + " "+ f)
  5     lines = stdout.readlines();
  6     return lines
  7     
  8 print my_tail("./my_log.txt",4)

可以将温度保存在列表中,并使用切片获取最后4个:

import re
import itertools
temps = []
infile = "/home/pi/Mysensor/Logs/test.log"
for line in open(infile):
    match = re.search('Temp=(\d+)', line)
    if match:
      test = match.group(1)
      temps.append(test)
print temps[:-5:-1]

若要查看有关切片的详细信息,see this post

我想这取决于你的日志文件有多大,但是我可以想出几种方法来做。在

最简单的方法可能是使用deque。在

from collections import deque
import re

temps = deque(maxlen=4)

infile = "/home/pi/Mysensor/Logs/test.log"
with open(infile, "r") as fh:
    for line in fh:
        match = re.search('Temp=(\d+)', line)
        if match:
            temp = match.group(1)
            temps.append(temp)

相关问题 更多 >