2010-07-20 61 views
35

我试图找到一个很好的方式来使用python实时读取日志文件。我希望在写入日志文件时逐行处理一行。不知何故,我需要不断尝试读取文件,直到它被创建,然后继续处理行,直到我终止该过程。有没有适当的方法来做到这一点?谢谢。从日志文件中读取,因为它正在使用Python编写

+0

这个也很好......我认为它符合你的标准,并提供一个可以轻松扩展的类。 [http://code.activestate.com/recipes/577968-log-watcher-tail-f-log/](http://code.activestate.com/recipes/577968-log-watcher-tail-f-log /) – mogga 2012-10-23 18:55:15

回答

20

你可以用这样的尝试:

import time 

while 1: 
    where = file.tell() 
    line = file.readline() 
    if not line: 
     time.sleep(1) 
     file.seek(where) 
    else: 
     print line, # already has newline 

例子来自here提取。

+0

这似乎是工作,但它不会允许我在我的Django应用程序中同时创建对象或写入数据库。我没有看到明显的原因。有一个简单的修复? – Anon 2010-07-20 19:37:12

+0

我不知道。我想你应该在一个单独的问题中发布一些代码来获得这个答案。我没有看到任何理由不让数据库更新,如果你把这个代码放在这个... – 2010-07-20 21:16:20

+0

得到这个工作,但我不得不把它弄乱了字符串之前,我可以把它写入我的数据库。谢谢。 – Anon 2010-07-21 18:23:43

-1

也许你可以做一个系统调用来

tail -f 

使用使用os.system()

32

看看this PDF开始在38页,幻灯片〜I-77,你会发现所有的你需要的信息。当然幻灯片的其余部分是惊人的,也是如此,但是那些专门与您的问题处理:

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 
+4

值得注意的是,这会跳过日志文件中的任何内容,只会在创建此迭代器后创建创建的“新”条目。此外,PDF真的是一个金矿;) – blented 2016-09-02 00:48:41

3

由于这是Python和日志标记,所以还有另一种可能性。

我认为这是基于Python记录器,基于logging.Handler。

您只需创建一个类,得到(命名)的记录器实例,并覆盖emit功能,把它放到一个GUI(如果你需要控制台只需添加一个控制台处理程序文件处理器)

例子:

import logging 

class log_viewer(logging.Handler): 
    """ Class to redistribute python logging data """ 

    # have a class member to store the existing logger 
    logger_instance = logging.getLogger("SomeNameOfYourExistingLogger") 

    def __init__(self, *args, **kwargs): 
     # Initialize the Handler 
     logging.Handler.__init__(self, *args) 

     # optional take format 
     # setFormatter function is derived from logging.Handler 
     for key, value in kwargs.items(): 
      if "{}".format(key) == "format": 
       self.setFormatter(value) 

     # make the logger send data to this class 
     self.logger_instance.addHandler(self) 

    def emit(self, record): 
     """ Overload of logging.Handler method """ 

     record = self.format(record) 

     # --------------------------------------- 
     # Now you can send it to a GUI or similar 
     # "Do work" starts here. 
     # --------------------------------------- 

     # just as an example what e.g. a console 
     # handler would do: 
     print(record) 

我目前使用类似的代码来添加一个TkinterTreectrl.Multilistbox在运行时查看记录器输出。

Off-Side:记录器只在初始化时才获取数据,因此如果您想让所有数据都可用,则需要在开始时对其进行初始化。 (我知道这是预料之中,但我认为值得提及。)

相关问题