25 python
我需要在python中模拟"tail -f",但我不想在读取循环中使用time.sleep.我想要一些更优雅的东西,如某种阻塞读取,或select.select超时,但python 2.6"选择"文档具体说:"它不能用于常规文件,以确定文件是否自上次读取后增长. " 还有其他方法吗?如果没有给出解决方案,我会在几天内阅读尾部的C源代码以试图找出它.我希望他们不要睡觉,呵呵谢谢.
MarioR
Tzu*_*hay 33
(更新)使用FS监视工具
或单次睡眠使用(我认为你更优雅).
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
Run Code Online (Sandbox Code Playgroud)
小智 11
为了最大限度地减少睡眠问题,我修改了Tzury Bar Yochay的解决方案,现在如果有活动则快速轮询,几秒钟没有活动,它只会每秒轮询一次.
import time
def follow(thefile):
thefile.seek(0,2) # Go to the end of the file
sleep = 0.00001
while True:
line = thefile.readline()
if not line:
time.sleep(sleep) # Sleep briefly
if sleep < 1.0:
sleep += 0.00001
continue
sleep = 0.00001
yield line
logfile = open("/var/log/system.log")
loglines = follow(logfile)
for line in loglines:
print line,
Run Code Online (Sandbox Code Playgroud)
ale*_*gle -3
你为什么不直接使用它subprocess.call自己tail呢?
subproces.call(['tail', '-f', filename])
Run Code Online (Sandbox Code Playgroud)
编辑:修复以消除额外的外壳进程。
Edit2:修复以消除已弃用的情况os.popen,从而消除插入参数、转义空格和其他内容的需要,然后运行 shell 进程。