我按照David Beazley先生的协程介绍模仿了tail -f
# a python version of tail -f
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
In [195]: !cat access_log
The first line
The second line
测试生成器功能
In [196]: logfile = open("access_log", "a+") #set append and write mode
In [197]: for line in follow(logfile):
...: print(line)
...:
然后我打开一个新的terminal2以将内容插入access_log
$ echo "This is the third line" >> access_log
$ echo "This is the fourth line" >> access_log
$ cat access_log
The first line
The second line
This is the third line
This is the fourth line
但是,在上一个终端中,for循环仍在挂起而不是跟随打印行,直到我终止它为止
In [197]: for line in follow(logfile):
...: print(line)
...:
^C---------------------------------------------------------------------------
KeyboardInterrupt Traceback (most recent call last)
<ipython-input-197-f4a72b70a34f> in <module>
----> 1 for line in follow(logfile):
2 print(line)
我的问题出了什么问题?