Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding the "tail -f in python"

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.

like image 975
Karl Yngve Lervåg Avatar asked Apr 12 '26 08:04

Karl Yngve Lervåg


1 Answers

(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.

like image 96
Sven Marnach Avatar answered Apr 13 '26 23:04

Sven Marnach



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!