从日志文件中读取,因为它是用python编写的

我试图find一个很好的方式来使用python实时读取日志文件。 我想从写入日志文件中逐行处理一行。 不知何故,我需要不断尝试读取文件,直到它被创build,然后继续处理行,直到我终止进程。 有没有适当的方法来做到这一点? 谢谢。

你可以尝试这样的事情:

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 

例子是从这里提取的。

看一下从第38页开始的这个PDF ,〜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 

由于这是Python和日志logging标记,还有另一种可能性来做到这一点。

我假设这是基于Pythonlogging器,基于logging.Handler。

您可以创build一个类来获取(named)logging器实例,并覆盖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 eg a console # handler would do: print(record) 

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

Off-Side:logging器在初始化时只获取数据,所以如果你想让所有的数据都可用,你需要在开始的时候初始化它。 (我知道这是预料之中,但我认为值得提及。)

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

 tail -f 

使用os.system()