python中flush和readline的详细信息
运行python中flush和readline的详细信息,python,operating-system,Python,Operating System,运行log.pybefurefollow.py它可以工作,就像tail-f一样,但是在log.py之前运行follow.py它不工作,如果我使用vim在文件中添加一些东西,访问日志,它也不工作 为什么? 在刷新之前不写入\0并且在读取之后读取\0它不继续还是其他什么 flush和readline的详细信息是什么 # log.py f = open("access-log","w") import time, random while True: time.sleep(random.r
log.py
befurefollow.py
它可以工作,就像tail-f
一样,但是在log.py
之前运行follow.py
它不工作,如果我使用vim在文件中添加一些东西,访问日志
,它也不工作
为什么?
在刷新之前
不写入\0
并且在读取之后
读取\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,
如果您首先运行
follow.py
,它将打开访问日志并不断尝试从中读取内容
但是随后出现了log.py
并调用open(“accesslog”,“w”)
,这将删除现有的accesslog
文件并创建一个新文件
由于follow.py
打开了原始文件,操作系统会为其保留一个文件句柄,但它不再是同一个文件名(事实上它根本没有名称)。follow.py
永远不知道创建的新文件,永远无法从原始文件句柄读取
也许
log.py
应该用“a”
而不是“w”
调用open?非常感谢