如何在Python中阻塞readline()以避免轮询?
我想监控一个正在写入的日志文件(就像使用tail -f命令那样),但是我不知道怎么让readline()在到达文件末尾时停下来。经过我在网上的搜索,找到的都是让程序不阻塞的解决方案。有没有人知道怎么让这个调用阻塞,这样我就不用频繁检查文件了?(我已经能做到频繁检查和休眠了,所以如果你建议这个,我会给你差评。)
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
1 个回答
0
你不能真的做到“在不轮询的情况下阻塞”。你必须在某个时刻检查一下文件是否有新数据给你。当你写一些不断更新的程序时,最终还是得轮询,除非你在用汇编语言写中断服务程序(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