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

查看:133
本文介绍了了解“tail -f in python”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个非常简单的python脚本:

pre $ def $ read_then_follow(file)
for line in file :
产生行
而真:
行= file.readline()
如果不行:
time.sleep(1.0)
继续
$ yield
$ b $ read_then_follow(some_file.txt):print line

文件some_file.txt包含几行文本,当我运行脚本时,这些文本将被写入屏幕。如果我然后用 echoline>> some_file.txt ,行会在1秒内打印到屏幕上。但是:如果我在 vim 中打开文件,在底部添加一行并保存,脚本将停止运行。它既不会将 vim 中写入的新行写入屏幕,也不会响应 echo ... 命令。



对于您的信息,我目前在Ubuntu 10.10上使用python 2.6.6。

解决方案

假设你使用的是类Unix操作系统。)

在vim中的保存实际上会创建一个名字相同的新的文件。磁盘。由脚本保存的文件句柄仍然指向文件,该文件不再有目录条目。如果您的脚本终止,那么旧文件的引用计数器将降为0,文件将被删除。


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.

解决方案

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

这篇关于了解“tail -f in python”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆