我正在为一个Web应用程序编写日志文件查看器,因此我想要通过日志文件的行进行分页。该文件中的项目是基于行的,最新的项目位于底部。
所以我需要一个tail()
方法,可以从底部读取n
行并支持偏移量。这是我想出来的:
def tail(f, n, offset=0):
"""Reads a n lines from f with an offset of offset lines."""
avg_line_length = 74
to_read = n + offset
while 1:
try:
f.seek(-(avg_line_length * to_read), 2)
except IOError:
# woops. apparently file is smaller than what we want
# to step back, go to the beginning instead
f.seek(0)
pos = f.tell()
lines = f.read().splitlines()
if len(lines) >= to_read or pos == 0:
return lines[-to_read:offset and -offset or None]
avg_line_length *= 1.3
这是一个合理的方法吗?推荐使用什么方法来带有偏移量地跟踪日志文件?
seek(0,2)
然后tell()
),并使用该值相对于开头进行查找。 - Anneopen
命令的参数以生成f
文件对象,因为根据f=open(..., 'rb')
或f=open(..., 'rt')
,必须以不同的方式处理f
。 - Dr Fabio Gori