【发布时间】:2016-01-22 18:26:12
【问题描述】:
根据David Beazley's talk on generators,以下代码应复制UNIX tail -f 命令:
import time
def follow(thefile):
thefile.seek(0,2)
while True:
line = thefile.readline()
if not line:
time.sleep(0.1)
continue
yield line
f = open('followed.txt')
lines = follow(f)
for i in lines:
print i
如果我在 shell 中运行它,它正在做“某事”,并且确实会锁定 IPython 笔记本,但它不会打印出 follow.txt 的内容。为什么会这样?
【问题讨论】:
-
你的方法适合我。
-
你是如何追加到
followed.txt的?如果您使用文本编辑器将文本添加到followed.txt,上面的代码可能不起作用,因为文本编辑器可能不会附加到原始文件——它可能正在创建一个新文件,然后将followed.txt重命名为它。 .. -
如果您
f = open('followed.txt', 'a')并同时调用f.write,或者(在 unix 上)使用echo "some text" >> followed.txt之类的东西附加,您发布的代码将起作用。 -
我在 windows 7 中使用了你的代码,并用 notepad++ 编辑了文件,效果很好
标签: python generator yield tail seek