Get last n lines of a file, similar to tail

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

    I found the Popen above to be the best solution. It's quick and dirty and it works For python 2.6 on Unix machine i used the following

    def GetLastNLines(self, n, fileName):
        """
        Name:           Get LastNLines
        Description:        Gets last n lines using Unix tail
        Output:         returns last n lines of a file
        Keyword argument:
        n -- number of last lines to return
        filename -- Name of the file you need to tail into
        """
        p = subprocess.Popen(['tail','-n',str(n),self.__fileName], stdout=subprocess.PIPE)
        soutput, sinput = p.communicate()
        return soutput
    

    soutput will have will contain last n lines of the code. to iterate through soutput line by line do:

    for line in GetLastNLines(50,'myfile.log').split('\n'):
        print line
    

提交回复
热议问题