python: read file continuously, even after it has been logrotated

前端 未结 3 2111
青春惊慌失措
青春惊慌失措 2021-02-03 13:28

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

while True:
    line = f.readline()
    if line:
        print lin         


        
3条回答
  •  轮回少年
    2021-02-03 14:31

    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.

    It could look like this:

    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)
    

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

提交回复
热议问题