从使用 python 写入的日志文件中读取 [英] Read from a log file as it's being written using python

查看:32
本文介绍了从使用 python 写入的日志文件中读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找到一种使用 python 实时读取日志文件的好方法.我想在写入时一次处理一个日志文件中的行.不知何故,我需要继续尝试读取文件,直到它被创建,然后继续处理行,直到我终止进程.有没有合适的方法来做到这一点?谢谢.

I'm trying to find a nice way to read a log file in real time using python. I'd like to process lines from a log file one at a time as it is written. Somehow I need to keep trying to read the file until it is created and then continue to process lines until I terminate the process. Is there an appropriate way to do this? Thanks.

推荐答案

你可以试试这样的:

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

示例摘自此处.

这篇关于从使用 python 写入的日志文件中读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆