一般我们通过tail -f
来实时刷新展示一些日志内容,这个功能其实可以通过几行代码就能做到:
#!/usr/bin/env python
import os
import sys
import select
LOGFILE = "/tmp/logs.log"
fp = open(LOGFILE, "r")
# move to end of the file
fp.seek(0, os.SEEK_END)
while(1):
r,w,e = select.select([fp.fileno()], [], [fp.fileno()])
if fp.fileno() in e:
sys.stderr.write("Error occured\n")
fp.close()
sys.exit(1)
if fp.fileno() in r:
while(1):
line = fp.readline()
if line == '':
break
sys.stdout.write(line)