2011-01-14 53 views
2

可能重复:
tail -f in python with no time.sleep我怎样才能阻止readline()在Python中,所以我不必投票?

我想监视正在写入(如尾-f)日志文件,我无法弄清楚如何使readline()阻塞一旦到达eof。我所有的搜索引擎都只是提出了一些解决方案,让事情不受阻碍。有没有人知道一种方式来打电话像这个块,所以我不必投票? (我完全能够轮询和睡眠的了,所以,如果你认为我要你而降低。)

fh = open('logfile') 
# I only want new output, so seek to the end of the file 
fh.seek(-1,2) 
while True: 
    # I want this to block until the file has new output, 
    # but it sees eof and returns '' immediately 
    line = fh.readline() 
    # ... process the line 
+3

你*确实知道`tail -f`民意调查,对吗? – 2011-01-14 19:04:32

+0

确定重复[tail -f在python中没有time.sleep](http://stackoverflow.com/questions/1475950/tail-f-in-python-with-no-time-sleep),但态度。 ..投票结束... – dawg 2011-01-14 19:56:22

回答

0

你不能真正“块无投票”。你检查文件是否有新的数据给你。当您不断更新进程时,除非您正在编写ISR(中断服务例程),否则必须最终进行轮询。即使如此,CPU仍在不断地轮询任何挂起的中断。

下面是你的代码,每秒钟检查文件中的新数据。这可以保持最低的CPU使用率。

fh = open('logfile') 
# I only want new output, so seek to the end of the file 
fh.seek(-1,2) 
# 'while True' is sort of bad style unless you have a VERY good reason. 
# Use a variable. This way you can exit nicely from the loop 
done = False 
while not done: 
    # I want this to block until the file has new output, 
    # but it sees eof and returns '' immediately 
    line = fh.readline() 
    if not line: 
     time.sleep(1) 
     continue 
    # ... process the line 
     #... if ready to exit: 
      done = True