我正在使用位于此处的用于处理无限数据的生成器,这是从文件返回尾部的非常简单的事情:
(来自这里的源代码)
# follow.py
#
# Follow a file like 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
# Example use
# Note : This example requires the use of an apache log simulator.
#
# Go to the directory run/foo and run the program 'logsim.py' from
# that directory. Run this program as a background process and
# leave it running in a separate window. We'll write program
# that read the output file being generated
#
if __name__ == '__main__':
logfile = open("run/foo/access-log","r")
loglines = follow(logfile)
for line in loglines:
print line,
我的问题是,当我写入测试文件“/var/log/test.log”时,它不会在我的生成器正在处理的控制台上打印任何内容。
我可以从其他终端打印文件并看到添加了新行,但是 python 代码似乎没有读取新数据?
我认为这可能是从 /var/log/ 读取的问题,所以我在 /Users/Me/Python/ 中创建了另一个文件,但它仍然不会读取数据。
我觉得我错过了一些非常简单的东西:(
编辑:
(我在 OSX,Python 2.7.5 顺便说一句)我逐行尝试,如下所示:
FID = open(fileName, 'r')
FID.seek(0,2)
FID.tell() # For example says 125
FID.readlines() # returns []
# Now I edit the log file, add in a couple of new lines (in TextMate if that helps)
FID.readlines() # returns []
FID.seek(0,2)
FID.tell() # returns 125
os.stat(fileName) # says size is 142
我的文件描述符没有读取更新的文件还是什么?