Reading infinite stream - tail

不问归期 提交于 2019-12-02 02:43:59

@ChristianDean in his comment answered your first question quite nicely, so I'll answer your second.

I do believe it is possible - you can use theFile's closed attribute and raise a StopIteration exception if the file was closed. Like this:

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

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

Your loop shall cease when the file is closed and the exception is raised.


A more succinct method (thanks, Christian Dean) that does not involve an explicit exception is to test the file pointer in the loop header.

def tail(theFile):
    theFile.seek(0, 2) 
    while not theFile.closed:
        line = theFile.readline()
        ...
        yield line
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!