Skip to content

Instantly share code, notes, and snippets.

@ls0f
Created April 19, 2016 08:46
Show Gist options
  • Select an option

  • Save ls0f/5a1b65395b107f3a5c6d55f6e12d0b99 to your computer and use it in GitHub Desktop.

Select an option

Save ls0f/5a1b65395b107f3a5c6d55f6e12d0b99 to your computer and use it in GitHub Desktop.
Python tail
import os
import time
import sys
class Tail(object):
def __init__(self, file_name):
self.filename = file_name
self.pos = 0
def locate(self, line_to_print):
with open(self.filename) as f:
f.seek(0, os.SEEK_END)
file_length = f.tell()
n = 0
while file_length > 0:
pos = file_length - 1024
pos = max(0, pos)
f.seek(pos)
buf = f.read(file_length - pos)
count = 0
for ch in buf[::-1]:
count += 1
if ch == '\n':
n += 1
if n > line_to_print:
self.pos = pos + len(buf) - count + 1
break
file_length = pos
def follow(self, n=5):
self.locate(line_to_print=n)
# print self.pos
with open(self.filename) as f:
f.seek(self.pos)
while 1:
line = f.readline()
if line:
sys.stdout.write(line)
else:
time.sleep(1)
if __name__ == "__main__":
t = Tail("test.txt")
t.follow(n=5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment