How can I tail a log file in Python?

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

    You could use the 'tailer' library: https://pypi.python.org/pypi/tailer/

    It has an option to get the last few lines:

    # Get the last 3 lines of the file
    tailer.tail(open('test.txt'), 3)
    # ['Line 9', 'Line 10', 'Line 11']
    

    And it can also follow a file:

    # Follow the file as it grows
    for line in tailer.follow(open('test.txt')):
        print line
    

    If one wants tail-like behaviour, that one seems to be a good option.

提交回复
热议问题