您的位置:首页技术文章
文章详情页

python - flush 和 readline 细节

【字号: 日期:2022-07-22 08:15:58浏览:64作者:猪猪

问题描述

先运行 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代表被编辑的文件名)

标签: Python 编程
相关文章: