Possible Duplicate:
tail -f in python with no time.sleep
我正在尝试监视正在写入的日志文件(如 tail -f),但我不知道如何在它到达 eof 时阻止 readline()。我所有的谷歌搜索都只找到了使事情成为非阻塞的解决方案。有谁知道像这个 block 一样调用电话的方法,所以我不必轮询? (我已经完全有能力轮询和 sleep 了,所以如果你建议我给你打分。)
fh = open('logfile')
# I only want new output, so seek to the end of the file
fh.seek(-1,2)
while True:
# I want this to block until the file has new output,
# but it sees eof and returns '' immediately
line = fh.readline()
# ... process the line
你不能真正地“不轮询就阻塞”。您必须在某个时候检查文件是否包含新数据。当你编写不断更新的进程时,你最终必须进行轮询,除非你在汇编中编写 ISR(中断服务例程)。即使这样,CPU 也会不断地轮询任何挂起的中断。
这是您的代码,每秒检查文件中是否有新数据。这使 CPU 使用率保持在最低限度。
fh = open('logfile')
# I only want new output, so seek to the end of the file
fh.seek(-1,2)
# 'while True' is sort of bad style unless you have a VERY good reason.
# Use a variable. This way you can exit nicely from the loop
done = False
while not done:
# I want this to block until the file has new output,
# but it sees eof and returns '' immediately
line = fh.readline()
if not line:
time.sleep(1)
continue
# ... process the line
#... if ready to exit:
done = True