python - 我怎样才能在 python 中阻止 readline(),这样我就不必轮询了?

标签 python

<分区>

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

关于python - 我怎样才能在 python 中阻止 readline(),这样我就不必轮询了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4694812/

相关文章:

python - 如何在 python 的文本文件中添加总数?

python - 提取不熟悉列表的值

python - 使用带有 graphql 查询的 API 在 R 上抛出 401 错误,但在 Python 上工作正常

python - 如何将带有项目评分的 df 转换为包含对一对项目进行评分的用户数量的 df ?

python - Ubuntu 16.04 pip 似乎坏了

通过消息代理进行 Java/Python 通信

python - 将日期字符串 (YYYY/YYYY_mm.mdf) 转换为可用的日期 Python

python - 对数字序列求和

python - 获取文件中的总行数和行索引的有效方法

Python 3.x 列表推导 VS 元组生成器