python - flush 和 readline 细节

查看:104
本文介绍了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, random
while 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.py

import time
def 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 use
if __name__ == '__main__':
    logfile = open("access-log")
    for line in follow(logfile):
        print line,

解决方案

问题在于, 你的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代表被编辑的文件名)

这篇关于python - flush 和 readline 细节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆