python - flush and readline details
我想大声告诉你
我想大声告诉你 2017-05-18 10:48:31
0
1
827

It is normal to run log.py first and then follow.py (it can have an effect similar to tail -f), but it is not possible to run follow.py first and then log.py, and it is done through vi access-log It is not possible to add the class content at the end because flush does not write \0, and readline does not read \0 continue or not? What is the specific underlying cause of this problem?

# 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,
我想大声告诉你
我想大声告诉你

reply all(1)
曾经蜡笔没有小新

The problem is that your log.py写得模式用了w, 如果你先打开follow.py, 并且thefile.seek(0,2), 那么它的偏移量肯定是最后的, 如果你的access-log有十万行, 总长度为100000字节, 那么thefile的位置就会去到第100000位置, 但是你的log.py却用了w, 这个模式会从头开始写, 所以直到log.py写到100000字节, 才会真正被follow.py接受到, 并且开始输出从100000位置后新增的内容.
解决办法:
换种写模式, 用APPENDappend mode is written:

f = open("access-log","a+")

The reason why the vimediting has no output is that when we use vim to edit a file, it is edited on a temporary file, not a real file. The temporary file name is ".xxx.swp" (xxx represents the file name being edited) )

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template