我正在尝试找到一种使用 python 实时读取日志文件的好方法。我想在写入时一次处理一个日志文件中的行。不知何故,我需要继续尝试读取文件,直到它被创建,然后继续处理行,直到我终止进程。有没有合适的方法来做到这一点?谢谢。
最佳答案
看看this PDF从第 38 页开始,~幻灯片 I-77,您将找到您需要的所有信息。当然,其余的幻灯片也很棒,但这些幻灯片专门针对您的问题:
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
关于python - 在使用 python 写入时从日志文件中读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3290292/