Skip to content

Instantly share code, notes, and snippets.

@chipchilders
Created April 16, 2012 20:33
Show Gist options
  • Save chipchilders/2401334 to your computer and use it in GitHub Desktop.
Save chipchilders/2401334 to your computer and use it in GitHub Desktop.
Tail in python
#!/usr/bin/python
import sys
import os
def main():
filename = sys.argv[len(sys.argv)-1]
targetlines = 10
countedlines = 0
default_chunk = os.statvfs(filename).f_bsize
size = os.path.getsize(filename)
lastposition = size
if size < default_chunk:
start_position = 0
chunk = size
elif size % default_chunk == 0:
start_position = size - default_chunk
chunk = default_chunk
else:
start_position = size - (size % default_chunk)
chunk = size % default_chunk
f = open(filename, 'r')
final_position_found = False
while start_position > -1 and not final_position_found:
f.seek(start_position)
block = f.read(chunk)
block_size = len(block)
position = block_size - 1
while position > -1:
if block[position] == "\n":
countedlines = countedlines + 1
if countedlines == targetlines + 1:
lastposition = block_size-position-1
final_position_found = True
break
position = position - 1
chunk = default_chunk
start_position = start_position - chunk
f.seek(size - lastposition)
out = f.read()
print out
f.close()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment