问题: 程序从文件末尾开始读取无限流中的行。
#解决办法:
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关闭时,生成器函数可以返回吗?
发布于 2017-07-04 01:23:36
@基督教迪恩在他的comment中很好地回答了你的第一个问题,所以我会回答你的第二个问题。
我相信这是可能的--如果文件被关闭,您可以使用theFile的closed属性并引发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 linehttps://stackoverflow.com/questions/44895527
复制相似问题