Understanding the “tail -f in python”

泪湿孤枕 提交于 2019-12-10 20:15:35

问题


I have created a very simple python script:

def read_then_follow(file):
    for line in file:
        yield line
    while True:
        line = file.readline()
        if not line:
            time.sleep(1.0)
            continue
        yield line

for line in read_then_follow("some_file.txt"): print line

The file "some_file.txt" contains a few lines of text, which will be written to screen when I run the script. If I then add a line to the file with echo "line" >> some_file.txt, the line will be printed to the screen within 1 second. But: if I open the file in vim, add a line at the bottom and save, the script stops to function. It neither writes the new line written in vim to screen nor respons to further echo ... commands.

For your information, I am currently using python 2.6.6 on Ubuntu 10.10.


回答1:


(I'm assuming you are on some Unix-like operating system.)

Saving in vim will actually create a new file with the same name on the disk. The file handle held by your script still points to the old file, which does not have a directory entry anymore. If your script terminates, the reference counter of the old file will drop to 0 and the file will be removed.



来源:https://stackoverflow.com/questions/5326405/understanding-the-tail-f-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!