简体   繁体   中英

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.

Why?

Before of flush does not write \\0 and after readline reading \\0 it does not continue or something else?

what's the details of flush and 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,

If you run follow.py first, it opens access-log and continually tries to read something from it.

But then log.py comes along and calls open("access-log", "w") which removes the existing access-log file and creates a new one.

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.

Perhaps log.py should call open with "a" instead of "w" ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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