我试图找到一个很好的方式来使用python实时读取日志文件。我希望在写入日志文件时逐行处理一行。不知何故,我需要不断尝试读取文件,直到它被创建,然后继续处理行,直到我终止该过程。有没有适当的方法来做到这一点?谢谢。从日志文件中读取,因为它正在使用Python编写
35
A
回答
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提取。
-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:记录器只在初始化时才获取数据,因此如果您想让所有数据都可用,则需要在开始时对其进行初始化。 (我知道这是预料之中,但我认为值得提及。)
相关问题
- 1. 如何读取日志从日志文件,因为它发生
- 2. 使用Python在日志文件中读取/写入特定行
- 3. 在Qt中读取文件,因为它正在写入
- 4. awk使用getline从文件读取数据,因为它正在写入
- 5. Python - 从正在Windows中编写的文本文件读取
- 6. python:使用正则表达式从日志文件中读取日期时间
- 7. 在java中读取当前正在写入的日志文件
- 8. 从日志文件中读取数据作为单独的应用程序正在写入它
- 9. 在Python中写入文件,使用Arduino从文件中读取
- 10. 获取日志文件,因为它是用弹性搜索
- 11. 使用python 2.7.9编写日志文件中的消息格式
- 12. 使用Java EE编写日志文件
- 13. 使用Powerpoint编写日志文件
- 14. 写在Python中的CSV文件,读取它使用列名
- 15. 正在从事件日志中阅读
- 16. 从python中的日志文件中读取特定列
- 17. 使用PHP读取IIS日志文件
- 18. 在c/C++中编写日志文件
- 19. 阅读日志文件,因为他们在更新中去
- 20. 亚马逊cloudwatch没有写入日志,因为它在实际文件中
- 21. 为php程序编写日志文件
- 22. 在java中读取日志文件
- 23. 在Python中读取日志文件并输出特定文本
- 24. 使用Java从日志文件中读取Stacktrace
- 25. 在日志文件上的读写
- 26. 从python中读取和写入文件
- 27. 从python中读取/写入android文件
- 28. 用C++编写/从文件读取
- 29. 读取日志文件并在jTextArea中显示它
- 30. 从csv文件中读取Python日期
这个也很好......我认为它符合你的标准,并提供一个可以轻松扩展的类。 [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