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,
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位置后新增的内容.解决办法:
换种写模式, 用
APPEND
append mode is written:The reason why the
vim
editing 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) )