做个笔记 : 利用python的 yield来实现一个生成器函数,然后调用这个生成器函数,这样当日志文件有变化时就打印新的行,代码如下:
import time
def follow(thefile):
thefile.seek(0,2)
while True:
line = thefile.readline()
if not line:
time.sleep(0.1)
continue
yield line
if __name__ == '__main__':
logfile = open('access-log','r')
loglines = follow(logfile)
for line in loglines:
print(line)
最后解释下seek()函数的用法,这个函数接收2个参数:file.seek(off, whence=0),从文件中移动off个(偏移量)操作标记(文件指针),正数往结束方向移动,负数往开始方向移动。如果设定了whence参数,就以whence设定的起始位为准,0代表从头开始,1代表当前位置,2代表文件最末尾位置。
原文链接 python实现实时监控文件的方法
网友评论