Get last n lines of a file, similar to tail

前端 未结 30 2923
挽巷
挽巷 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:11

    Not the first example using a deque, but a simpler one. This one is general: it works on any iterable object, not just a file.

    #!/usr/bin/env python
    import sys
    import collections
    def tail(iterable, N):
        deq = collections.deque()
        for thing in iterable:
            if len(deq) >= N:
                deq.popleft()
            deq.append(thing)
        for thing in deq:
            yield thing
    if __name__ == '__main__':
        for line in tail(sys.stdin,10):
            sys.stdout.write(line)
    

提交回复
热议问题