I have created a 开发者_StackOverflow社区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.
(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.
精彩评论