发电机无控制台输出

2024-05-21 01:17:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着跟着一个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的一个实现,它从末尾逐行读取文件

但是,运行此命令不会在控制台中产生任何输出,除了闪烁的光标

关于为什么不打印文件的行有什么建议吗


Tags: the代码import示例iftimeondef
2条回答

此脚本仅打印附加到文件的数据。如果文件中有任何预先存在的数据或文本,则函数follow(thefile)不会返回它

你的代码总是sleep在执行continue,因为在你用thefile.seek(0,2)搜索到文件的末尾之后,就没有什么可读的了

当你在一个永无止境的循环(while True:)中这样做时,你永远不会到达yield line并且永远循环而没有任何输出

相关问题 更多 >