tail -f 在 python 中没有 time.sleep [英] tail -f in python with no time.sleep
问题描述
我需要在 python 中模拟tail -f",但我不想在阅读循环中使用 time.sleep.我想要一些更优雅的东西,比如某种阻塞读取,或者 select.select 超时,但 python 2.6select"文档特别指出:它不能用于常规文件来确定自上次读取以来文件是否增长."还有什么办法吗?几天后,如果没有给出解决方案,我将阅读 tail 的 C 源代码以试图弄清楚.我希望他们不要用睡眠,嘿嘿谢谢.
I need to emulate "tail -f" in python, but I don't want to use time.sleep in the reading loop. I want something more elegant like some kind of blocking read, or select.select with timeout, but python 2.6 "select" documentation specifically says: "it cannot be used on regular files to determine whether a file has grown since it was last read." Any other way? In a few days if no solution is given I will read tail's C source code to try to figure it out. I hope they don't use sleep, hehe Thanks.
马里奥
推荐答案
(update)要么使用FS监控工具
(update) Either use FS monitors tools
或者单次睡眠使用(我认为这更优雅).
Or a single sleep usage (which I would you consider as much more elegant).
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
这篇关于tail -f 在 python 中没有 time.sleep的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!