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
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