python - flush 和 readline 细节
问题描述
先运行 log.py 再运行 follow.py 正常(可以有类似 tail -f 的效果),但是先运行 follow.py 再运行 log.py 不可以,而且过通过 vi 在 access-log 最后添加类容,也不可以,是因为 flush 不写 0,readline 读到 0 就不继续吗?这个问题具体底层是什么原因?
# log.py f = open('access-log','w')import time, randomwhile True: time.sleep(random.random()) n = random.randint(0,len(ips)-1) m = random.randint(0,len(docs)-1) t = time.time() date = time.strftime('[%d/%b/%Y:%H:%M:%S -0600]',time.localtime(t)) print >>f,'%s - - %s %s' % (ips[n],date,docs[m]) f.flush()
# follow.pyimport timedef follow(thefile): thefile.seek(0,2) # Go to the end of the file while True: line = thefile.readline() if not line: time.sleep(0.1) # Sleep briefly continue yield line# Example useif __name__ == ’__main__’: logfile = open('access-log') for line in follow(logfile):print line,
问题解答
回答1:问题在于, 你的log.py写得模式用了w, 如果你先打开follow.py, 并且thefile.seek(0,2), 那么它的偏移量肯定是最后的, 如果你的access-log有十万行, 总长度为100000字节, 那么thefile的位置就会去到第100000位置, 但是你的log.py却用了w, 这个模式会从头开始写, 所以直到log.py写到100000字节, 才会真正被follow.py接受到, 并且开始输出从100000位置后新增的内容.解决办法:换种写模式, 用APPEND追加的模式写:
f = open('access-log','a+')
而vim编辑没有输出的原因是, 当我们用vim编辑文件时, 是编辑在一个临时文件上, 并不是真正的文件, 临时文件名是'.xxx.swp' (xxx代表被编辑的文件名)
相关文章:
1. android有ldpi, mdpi, hdpi, xhdpi这些drawable文件夹,系统是依据什么去选择的?2. angular.js - angularjs 与requirejs集成3. android - textview在获取网络数据填充之后,占据的是默认的大小,点击之后才会包裹内容。4. Java 在内部类中访问变量。需要宣布为最终5. Java中的多人游戏。将客户端(玩家)连接到其他客户端创建的游戏6. html - 特殊样式按钮 点击按下去要有凹下和弹起的效果7. angular.js - ng-grid 和tabset一起用时,grid width默认特别小8. mysql中 when then 的优化9. html5 - 在一个页面中 初始了两个swiper 不知道哪里错了 一直不对10. html - CSS3能写出这种环状吗,不是环形进度条?
