python:连续读取文件,即使它已经被logrotated [英] python: read file continuously, even after it has been logrotated

查看:56
本文介绍了python:连续读取文件,即使它已经被logrotated的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的python脚本,可在其中连续读取日志文件(与tail -f相同)

I have a simple python script, where I read logfile continuosly (same as tail -f)

while True:
    line = f.readline()
    if line:
        print line,
    else:
        time.sleep(0.1)

通过logrotate旋转日志文件后,如何确保仍可以读取日志文件?

How can I make sure that I can still read the logfile, after it has been rotated by logrotate?

即我需要做与tail -F一样的事情.

i.e. I need to do the same what tail -F would do.

我正在使用python 2.7

推荐答案

只要您只打算在Unix上这样做,最可靠的方法可能就是检查,以使打开的文件仍引用相同的 i节点作为名称,如果情况不再如此,请重新打开它.您可以在st_ino字段中从os.statos.fstat获取文件的编号.

As long as you only plan to do this on Unix, the most robust way is probably to check so that the open file still refers to the same i-node as the name, and reopen it when that is no longer the case. You can get the i-number of the file from os.stat and os.fstat, in the st_ino field.

它可能看起来像这样:

import os, sys, time

name = "logfile"
current = open(name, "r")
curino = os.fstat(current.fileno()).st_ino
while True:
    while True:
        buf = current.read(1024)
        if buf == "":
            break
        sys.stdout.write(buf)
    try:
        if os.stat(name).st_ino != curino:
            new = open(name, "r")
            current.close()
            current = new
            curino = os.fstat(current.fileno()).st_ino
            continue
    except IOError:
        pass
    time.sleep(1)

我怀疑这在Windows上是否有效,但是由于您使用的是tail的说法,所以我想这不是问题. :)

I doubt this works on Windows, but since you're speaking in terms of tail, I'm guessing that's not a problem. :)

这篇关于python:连续读取文件,即使它已经被logrotated的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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