我有一个Apache服务器写入自定义日志文件(通过cgi脚本)。我还有一个Python脚本,定期获取该日志文件的尾部。这是我的尾巴功能:
def tail(f, window = 1):
f = open(f, 'r')
BUFSIZ = 1024
f.seek(0, 2)
bytes = f.tell()
size = window
block = -1
data = []
while size > 0 and bytes > 0:
if (bytes - BUFSIZ > 0):
# Seek back one whole BUFSIZ
f.seek(block*BUFSIZ, 2)
# read BUFFER
data.append(f.read(BUFSIZ))
else:
# file too small, start from begining
f.seek(0,0)
# only read what was not read
data.append(f.read(bytes))
linesFound = data[-1].count('\n')
size -= linesFound
bytes -= BUFSIZ
block -= 1
f.close()
return '\n'.join(''.join(data).splitlines()[-window:])
单独来看,Python脚本和Apache日志记录都可以正常工作。但是,当我让它们同时处理同一个日志文件时,日志文件将不再更新。
如何在Python中实现不会干扰Apache写入的尾部读取函数?