Skip to content

Instantly share code, notes, and snippets.

@xintron
Created January 17, 2013 08:21
Show Gist options
  • Save xintron/4554511 to your computer and use it in GitHub Desktop.
Save xintron/4554511 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
# encoding: utf-8
import os
import sys
import argparse
def parse_arguments():
parser = argparse.ArgumentParser()
parser.add_argument('file')
parser.add_argument('-l', '--lines', type=int, default=10,
help='Specify number of lines to fetch. Default: 10.')
args = parser.parse_args()
return args
def main():
args = parse_arguments()
# Use 256 bytes as the "base" for one line
chunk_size = 256*args.lines
with open(args.file, 'r') as f:
f.seek(0, os.SEEK_END)
size = f.tell()
lines = []
data = ''
while len(lines) < args.lines:
pos = f.tell()-chunk_size
if pos < 0:
f.seek(0)
data = f.read(chunk_size - pos)+data
lines = data.split('\n') + lines
break
f.seek(pos)
data = f.read(chunk_size)+data
if '\n' in data:
s = data.split('\n')
lines = s[1:] + lines
data = s[0]
for line in lines[-args.lines:]:
print(line, end='\n')
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment