从文件中仅获取新行 [英] Get only new lines from file
问题描述
当前我有这段代码,但是它读取了所有行,然后使用while True语句监视文件:
Currently i have this piece of code, but it reads all lines, and then watch the file with the while True statement:
with open('/var/log/logfile.log') as f:
while True:
line = f.readline()
if not line:
time.sleep(1)
else:
print(line)
打开文件时,实际上我只需要在已经检测到的行之后添加新行-谁能帮帮我?也许比while语句更好地观看它?
I actually only need new lines coming after the lines already detected when opening the file - anybody who can help me out? Maybe a better way to watch it aswell, than with the while statement?
另一个问题是,在Linux计算机上,该脚本实际上是在锁定文件,因此无法将其写入,然后再次关闭该脚本.在OS X上可以正常工作.解决这个问题的想法也可能很好.
Another problem is that on Linux machines the script is actually locking the file so it can not be written to, before i close the script again. On OS X it works fine. Could also be nice with an idea to work around this.
希望那里有人正在从事类似的工作.
Hope there is somebody out there who have been working with something similar.
推荐答案
您最初可以完全读取文件,然后将其关闭,并在其上保留更改监视器,该监视器在下面使用轮询实现.
You could initially read the file completely, then close it, and keep a change monitor over it, this monitor is implemented below using polling.
import time
filePath = '/var/log/logfile.log'
lastLine = None
with open(filePath,'r') as f:
while True:
line = f.readline()
if not line:
break
print(line)
lastLine = line
while True:
with open(filePath,'r') as f:
lines = f.readlines()
if lines[-1] != lastLine:
lastLine = lines[-1]
print(lines[-1])
time.sleep(1)
但是您也可以使用以下工具中描述的工具:检测文件更改而不进行轮询
But you could also use tools like those described at: Detect File Change Without Polling
这篇关于从文件中仅获取新行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!