【发布时间】:2013-08-23 08:32:21
【问题描述】:
我正在使用位于here 的用于处理无限数据的生成器,这是从文件中返回尾部的非常简单的事情:
(源代码来自here)
# 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
是我的文件描述符没有读取更新的文件还是什么?
【问题讨论】:
-
你能把你拥有的东西发布出来
-
我已经在我的机器上尝试过你的代码,它可以工作......你的环境是什么?
-
确实,对我也有用。
-
我在 OSX 上,除了它当前指向我的 /dev/Python/ 文件夹中的文件外,我所拥有的与上面完全相同。我已经验证我可以打开它并将其输出到屏幕上,但它不会抓取新内容,因为它们已保存到文件中
-
注意:跟随文件描述符不同于按名称跟随文件,例如,如果您正在手动编辑文件;您的编辑器可能会使用
rename来保存用于编辑的临时文件,而不是附加到原始文件中。比较tail -f和tail -F的输出以查看差异(后者可能会使用inotify或类似的功能让您的操作系统监视文件的目录,或者如果文件多次未更改,它可能只是按名称重新打开文件迭代)。