通过 readline 读取动态更新的日志文件

Reading a dynamically updated log file via readline

我正在尝试通过 readline 逐行读取日志文件。 我很惊讶地观察到以下行为(在解释器中执行的代码,但从文件执行变体时也会发生同样的情况):

f = open('myfile.log')
line = readline()
while line:
  print(line)
  line = f.readline()
# --> This displays all lines the file contains so far, as expected
    
# At this point, I open the log file with a text editor (Vim),
# add a line, save and close the editor.

line = f.readline()
print(line)
# --> I'm expecting to see the new line, but this does not print anything!

这种行为标准吗?我错过了什么吗?

注意:我知道有更好的方法来处理更新的文件,例如使用此处指出的生成器:Reading from a frequently updated file。我只是想了解这个精确用例的问题。

对于您的特定用例,解释是 Vim 使用了写入临时策略。这意味着所有的写操作都是在一个临时文件上进行的。

相反,您的脚本从原始文件读取,因此看不到任何更改。


为了进一步测试,您可以尝试使用以下方式直接写入文件,而不是 Vim:

echo "Hello World" >> myfile.log

您应该会看到来自 python 的新行。

要关注您的文件,您可以使用此代码:

f = open('myfile.log')

while True:
    line = readline()
    if not line:
        print(line)