运行log.py befure follow.py --就像tail -f一样--但是在log.py之前运行follow.py --它不工作,如果我在文件中使用vim add,access-log,则两者都不工作。
为什么?
在flush之前不写\0,在readline读取\0之后,它不再继续,还是其他什么东西?
flush和readline的细节是什么?
# 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,发布于 2017-05-12 04:03:48
如果您首先运行follow.py,它将打开access-log并不断尝试从其中读取某些内容。
但是随后log.py出现并调用open("access-log", "w"),它删除现有的access-log文件并创建一个新的文件。
由于follow.py打开了原始文件,操作系统为它维护了一个文件句柄,但它不再是同一个文件名了(实际上它根本没有名字。) follow.py永远不知道创建的新文件,并且永远无法从原始文件句柄读取文件句柄。
也许log.py应该用"a"而不是"w"调用open
https://stackoverflow.com/questions/43928910
复制相似问题