Get last n lines of a file, similar to tail

前端 未结 30 3082
挽巷
挽巷 2020-11-22 03:46

I\'m writing a log file viewer for a web application and for that I want to paginate through the lines of the log file. The items in the file are line based with the newest

30条回答
  •  礼貌的吻别
    2020-11-22 04:12

    Update for answer given by A.Coady

    Works with python 3.

    This uses Exponential Search and will buffer only N lines from back and is very efficient.

    import time
    import os
    import sys
    
    def tail(f, n):
        assert n >= 0
        pos, lines = n+1, []
    
        # set file pointer to end
    
        f.seek(0, os.SEEK_END)
    
        isFileSmall = False
    
        while len(lines) <= n:
            try:
                f.seek(f.tell() - pos, os.SEEK_SET)
            except ValueError as e:
                # lines greater than file seeking size
                # seek to start
                f.seek(0,os.SEEK_SET)
                isFileSmall = True
            except IOError:
                print("Some problem reading/seeking the file")
                sys.exit(-1)
            finally:
                lines = f.readlines()
                if isFileSmall:
                    break
    
            pos *= 2
    
        print(lines)
    
        return lines[-n:]
    
    
    
    
    with open("stream_logs.txt") as f:
        while(True):
            time.sleep(0.5)
            print(tail(f,2))
    
    

提交回复
热议问题