How can I tail a log file in Python?

前端 未结 12 2401
故里飘歌
故里飘歌 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:15

    All the answers that use tail -f are not pythonic.

    Here is the pythonic way: ( using no external tool or library)

    def follow(thefile):
         while True:
            line = thefile.readline()
            if not line or not line.endswith('\n'):
                time.sleep(0.1)
                continue
            yield line
    
    
    
    if __name__ == '__main__':
        logfile = open("run/foo/access-log","r")
        loglines = follow(logfile)
        for line in loglines:
            print(line, end='')
    

提交回复
热议问题