Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 发电机无控制台输出_Python - Fatal编程技术网

Python 发电机无控制台输出

Python 发电机无控制台输出,python,Python,我正试着跟随一个新的方向。 示例代码如下所示: 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 con

我正试着跟随一个新的方向。 示例代码如下所示:

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

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


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

您的代码总是
睡眠
并执行
继续
,就像您用
文件搜索到文件末尾一样。seek(0,2)
将没有任何内容可读取


当您在一个永不结束的循环中执行此操作时(
,而True:
),您永远不会到达
屈服线,并且永远循环而没有任何输出。

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

不会返回该数据或文本。开始运行该文件后,该文件是否会更新?否,在单独的窗口中是静态文件,请尝试
echo hello>>我的文件
(请注意双重
)。然后,单词
hello
应该出现在Python窗口中。他正在尝试模仿
tail-f
。如果外部进程随后写入文件并扩展其结尾,则最终会有一些内容需要读取。@Robᵩ, 但问题中显示的行为是因为没有什么可打印的,这就是问题“没有可打印的”——是的,这就是问题所在。不是他的代码不正确,而是他的测试不正确。当提供了打印的东西时,他的代码工作得完美无缺。您的回答似乎暗示OP的解决方案在于修改他的代码。