Skip to content

Instantly share code, notes, and snippets.

@kakty3
Forked from amitsaha/tail.py
Last active August 29, 2015 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kakty3/d44bdd3025228e057012 to your computer and use it in GitHub Desktop.
Save kakty3/d44bdd3025228e057012 to your computer and use it in GitHub Desktop.
'''
Basic tail command implementation
Usage:
tail.py filename numlines
'''
import sys
import linecache
if len(sys.argv) !=3:
print 'Usage: tail.py <file> <nlines>'
sys.exit(1)
# filename and number of lines requested
fname, nlines = sys.argv[1:]
nlines = int(nlines)
# count the total number of lines
tot_lines = len(open(fname).readlines())
# use line cache module to read the lines
for i in range(tot_lines - nlines + 1, tot_lines+1):
print linecache.getline(sys.argv[1],i),
""" This is a more efficient version, since it does not read the entire
file
"""
import sys
import os
lines = int(sys.argv[1])
if lines == 0:
sys.exit('')
fname = sys.argv[2]
fsize = os.stat(fname).st_size
bufsize = 80
iter = 0
with open(sys.argv[2]) as f:
if bufsize > fsize:
bufsize = fsize - 1
data = []
while True:
iter += 1
offset = max(0, fsize - bufsize * iter)
f.seek(offset)
if offset == 0:
print ''.join(f.readlines())
break
data = f.readlines()
if len(data) > lines or f.tell() == 0:
print(''.join(data[-lines:]))
break
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment