阅读无限流-tail

Reading infinite stream - tail

Problem:

Program to read the lines from infinite stream starting from its end of file.

#解决方案:

import time
def tail(theFile):
    theFile.seek(0,2)   # Go to the end of the file
    while True:
        line = theFile.readline()
        if not line:
            time.sleep(10)    # Sleep briefly for 10sec
            continue
        yield line

if __name__ == '__main__':
    fd = open('./file', 'r+')
    for line in tail(fd):
        print(line)

readline() 是非阻塞读取,如果检查每一行。

问题:

这对我的程序没有意义 运行 无限等待,在写入文件的进程有 close()

1) 此代码的 EAFP 方法是什么,以避免 if

2) 生成器函数 return 可以返回 file 关闭吗?

@ChristianDean 在他的 中很好地回答了你的第一个问题,所以我会回答你的第二个问题。

我相信这是可能的 - 您可以使用 theFileclosed 属性并在文件关闭时引发 StopIteration 异常。像这样:

def tail(theFile):
    theFile.seek(0, 2) 
    while True:
        if theFile.closed:
            raise StopIteration

        line = theFile.readline()
        ...
        yield line

当文件关闭并引发异常时,您的循环将停止。


不涉及显式异常的更简洁的方法(感谢 Christian Dean)是测试循环头中的文件指针。

def tail(theFile):
    theFile.seek(0, 2) 
    while not theFile.closed:
        line = theFile.readline()
        ...
        yield line