How can I tail a log file in Python?

前端 未结 12 2526
故里飘歌
故里飘歌 2020-11-22 10:50

I\'d like to make the output of tail -F or something similar available to me in Python without blocking or locking. I\'ve found some really old code to do that here, but I\'

12条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-22 10:59

    Ideally, I'd have something like tail.getNewData() that I could call every time I wanted more data

    We've already got one and itsa very nice. Just call f.read() whenever you want more data. It will start reading where the previous read left off and it will read through the end of the data stream:

    f = open('somefile.log')
    p = 0
    while True:
        f.seek(p)
        latest_data = f.read()
        p = f.tell()
        if latest_data:
            print latest_data
            print str(p).center(10).center(80, '=')
    

    For reading line-by-line, use f.readline(). Sometimes, the file being read will end with a partially read line. Handle that case with f.tell() finding the current file position and using f.seek() for moving the file pointer back to the beginning of the incomplete line. See this ActiveState recipe for working code.

提交回复
热议问题