How can I tail a log file in Python?

前端 未结 12 2555
故里飘歌
故里飘歌 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 11:06

    Adapting Ijaz Ahmad Khan's answer to only yield lines when they are completely written (lines end with a newline char) gives a pythonic solution with no external dependencies:

    def follow(file) -> Iterator[str]:
        """ Yield each line from a file as they are written. """
        line = ''
        while True:
            tmp = file.readline()
            if tmp is not None:
                line += tmp
                if line.endswith("\n"):
                    yield line
                    line = ''
            else:
                time.sleep(0.1)
    
    
    if __name__ == '__main__':
        for line in follow(open("test.txt", 'r')):
            print(line, end='')
    

提交回复
热议问题