我试着跟着一个tutorial on Python coroutines。 示例代码如下:
import time
def follow(thefile):
thefile.seek(0,2) # Go to the end of the file
while True:
line = thefile.readline()
if not line:
time.sleep(0.1) # Sleep briefly
continue
yield line
# Example use
if __name__ == '__main__':
logfile = open("my-file")
for line in follow(logfile):
print(line)
这应该是Unix tail-f
的一个实现,它从末尾逐行读取文件
但是,运行此命令不会在控制台中产生任何输出,除了闪烁的光标
关于为什么不打印文件的行有什么建议吗
此脚本仅打印附加到文件的数据。如果文件中有任何预先存在的数据或文本,则函数
follow(thefile)
不会返回它你的代码总是
sleep
在执行continue
,因为在你用thefile.seek(0,2)
搜索到文件的末尾之后,就没有什么可读的了当你在一个永无止境的循环(
while True:
)中这样做时,你永远不会到达yield line
并且永远循环而没有任何输出相关问题 更多 >
编程相关推荐