简体   繁体   English

理解“tail -f in python”

[英]Understanding the “tail -f in python”

I have created a very simple python script: 我创建了一个非常简单的python脚本:

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. 文件“some_file.txt”包含几行文本,在运行脚本时将写入屏幕。 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. 如果我然后使用echo "line" >> some_file.txt在文件中添加一行,该行将在1秒内打印到屏幕上。 But: if I open the file in vim , add a line at the bottom and save, the script stops to function. 但是:如果我在vim中打开文件,在底部添加一行并保存,脚本将停止运行。 It neither writes the new line written in vim to screen nor respons to further echo ... commands. 它既不会将用vim写的新行写入屏幕,也不会echo ...进一步的echo ...命令。

For your information, I am currently using python 2.6.6 on Ubuntu 10.10. 为了您的信息,我目前在Ubuntu 10.10上使用python 2.6.6。

(I'm assuming you are on some Unix-like operating system.) (我假设你使用的是类Unix操作系统。)

Saving in vim will actually create a new file with the same name on the disk. 保存在vim中实际上会在磁盘上创建一个具有相同名称的文件。 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. 如果脚本终止,则旧文件的引用计数器将降为0,文件将被删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM