我需要在 python 中模拟“tail -f”,但我不想在阅读循环中使用 time.sleep。我想要一些更优雅的东西,比如某种阻塞读取,或者 select.select 超时,但是 python 2.6“选择”文档特别说:“它不能用于常规文件来确定文件自上次读取以来是否已经增长。 " 还有什么办法吗? 几天后,如果没有给出解决方案,我将阅读 tail 的 C 源代码以尝试解决。我希望他们不要使用 sleep ,呵呵 谢谢。
马里奥
最佳答案
(更新) 要么使用 FS 监控工具
或单次 sleep 使用(我认为您认为更优雅)。
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
logfile = open("access-log")
loglines = follow(logfile)
for line in loglines:
print line
关于python - 没有时间的python中的tail -f.sleep,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1475950/