读无限流-尾巴 [英] 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()
是非阻塞读取,是否检查每一行.
readline()
is a non-blocking read, with if check for every line.
问题:
在写入文件的进程具有close()
It does not make sense for my program running to wait infinitely, after the process writing to file has close()
1)为了避免if
,此代码的EAFP方法是什么?
1) What would be the EAFP approach for this code, to avoid if
?
2)生成器功能可以在file
关闭时返回吗?
2) Can generator function return back on file
close?
推荐答案
@ChristianDean在他的评论很好地回答了您的第一个问题,因此我将回答您的第二个问题.
@ChristianDean in his comment answered your first question quite nicely, so I'll answer your second.
我确实相信这是可能的-如果文件已关闭,则可以使用theFile
的closed
属性并引发StopIteration
异常.像这样:
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.
不涉及显式异常的更简洁的方法(感谢Christian Dean)是在循环头中测试文件指针.
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
这篇关于读无限流-尾巴的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!