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. mysql - 我的myeclipse一直连显示数据库连接失败,不知道为什么2. docker网络端口映射,没有方便点的操作方法么?3. c++ - QWebEngineView加载url后直接点击链接没有反应要怎么解决?4. 为什么redis中incr一个“0” 会报错?5. python的MySQLdb库中的executemany方法如何改变默认加上的单引号?6. javascript - 一个字符串转换成数字,例子就是a="2,322.222",b=’1,211.21’,如何在angualr中执行相减7. 看不懂你这一步的操作8. python爬虫 - scrapy使用redis的时候,redis需要进行一些设置吗?9. angular.js - angular指令中的scope属性中用&获取父作用域函数的问题10. 前端HTML与PHP+MySQL连接

网公网安备