boyeestudio wrote: > The following program have the same function as the linux's command:tail > -f logfile.log > But it print a lot of blank lines while showing on the stdout. > How to fix this problem and let it go ahead always > showing the end line as the log file's increasing. > > #tail.py: > > import os > import sys > > class Tail: > def __init__(self,inputstream): > self.inputstream=inputstream > > def tail(self): > self.inputstream.seek(0,2) ???Maybe this is where I'll need > fixed,But I don't know how to....
You probably want to move to the end of the file once at the beginning of the script, not before every attempt to read from it... > line=self.inputstream.readline().strip() Don't strip() so fast. You lose the information whether you have reached the (current) end of file or a blank line (readline() returns "" or "\n" respectively). > print line > > if __name__=="__main__": > if len(sys.argv)<=1: > print "You must type a log file name" > sys.exit() > arg=file(sys.argv[1],'r+') > while(arg): That's always true, I think. > try: > t=Tail(arg) > t.tail() > except KeyboardInterrupt: > arg.close() > print "File closed" A no-fluff version might be filename = sys.argv[1] infile = open(filename, "r") infile.seek(0, 2) while True: while True: line = infile.readline() if not line: # an empty string indicates eof break print line, time.sleep(1) # give the writing program a chance to write more lines The inner loop can also be written for line in iter(infile.readline, ""): print line, Peter -- http://mail.python.org/mailman/listinfo/python-list