yield版本的tail -f
import time
def follow(thefile):
thefile.seek(0,2) # 备注1
while True:
line = thefile.readline()
if not line:
time.sleep(0.1) # 备注2
continue
yield line
# Example use
if __name__ == '__main__':
logfile = open("/var/log/message")
for line in follow(logfile):
print line,
备注1: seek函数有两个参数
第一个参数: 表示从当前行的第x字符开始读取到该行的最后一个字符, 例如填写0则表示从第0个字符开始读取一直到该行的最后一个字符; 如果填写10则表示从当前行的第十个字符开始读取到当前行的最后一个字符.
第二个参数: 有三个值, 0表示从文件第一行开始读取, 1表示从接着上次的位置开始读取, 2表示从文件的最后一行开始读取.
备注2: 通过利用time.sleep, 让程序进入休眠状态, 避免io读写过于凶猛.
其他版本的tail -f(没有yield)
# -.- coding:utf-8 -.-
# __author__ = 'zhengtong'
import time
def follow(thefile):
thefile.seek(0, 2)
while True:
current_position = thefile.tell() # 备注3
line = thefile.readline()
if line:
print line
else:
thefile.seek(current_position) # 备注4
time.sleep(0.1)
if __name__ == '__main__':
logfile = open('/var/log/message')
follow(logfile)
备注3: 利用tell将当前所在的位置, 如果没有读取到新的数据则会结合seek(current_position)持续锁定当前位置.
参考资料: http://www.dabeaz.com/coroutines/index.html