首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >读取无限流尾

读取无限流尾
EN

Stack Overflow用户
提问于 2017-07-04 00:56:22
回答 1查看 2.4K关注 0票数 3

问题: 程序从文件末尾开始读取无限流中的行。

#解决办法:

代码语言:javascript
复制
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()是一种非阻塞读取,每一行都有if检查.

问题:

在编写文件的过程有close()之后,我的程序无限地等待是没有意义的。

1)为避免if,本代码的EAFP方法是什么?

( 2)在file关闭时,生成器函数可以返回吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-07-04 01:23:36

@基督教迪恩在他的comment中很好地回答了你的第一个问题,所以我会回答你的第二个问题。

我相信这是可能的--如果文件被关闭,您可以使用theFileclosed属性并引发StopIteration异常。

代码语言:javascript
复制
def tail(theFile):
    theFile.seek(0, 2) 
    while True:
        if theFile.closed:
            raise StopIteration

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

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

一个更简洁的方法(谢谢,Christian Dean)不涉及明确的异常,就是测试循环头中的文件指针。

代码语言:javascript
复制
def tail(theFile):
    theFile.seek(0, 2) 
    while not theFile.closed:
        line = theFile.readline()
        ...
        yield line
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44895527

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档