简体   繁体   English

python中的刷新和readline的详细信息

[英]detail of flush and readline in python

run log.py befure follow.py it works, just like tail -f , but run follow.py before log.py it does NOT work, and if I use vim add something in file, access-log , it does NOT work neither. 运行log.py befure follow.py它的工作原理,就像tail -f ,但运行follow.py之前log.py它不工作,如果我使用vim在文件中添加一些access-log ,这是行不通的既不。

Why? 为什么?

Before of flush does not write \\0 and after readline reading \\0 it does not continue or something else? 之前flush不写\\0readline\\0它不会继续或其他什么东西?

what's the details of flush and readline ? flushreadline的详细信息是什么?

# 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,

If you run follow.py first, it opens access-log and continually tries to read something from it. 如果先运行follow.py ,它将打开访问日志并不断尝试从中读取内容。

But then log.py comes along and calls open("access-log", "w") which removes the existing access-log file and creates a new one. 但是随后log.py出现并调用open("access-log", "w") ,它删除了现有的access-log文件并创建了一个新文件。

Since follow.py had the original file open, the operating system maintains a file handle to it, but it isn't the same filename anymore (in fact it has no name at all.) follow.py never knows about the new file that was created, and is stuck reading from the original file handle forever. 由于follow.py已打开原始文件,因此操作系统会维护该文件的文件句柄,但文件名不再相同(实际上根本没有名称) follow.py永远都不知道新文件已创建,并且永远无法读取原始文件句柄。

Perhaps log.py should call open with "a" instead of "w" ? 也许log.py应该使用"a"而不是"w"来调用open?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM