Last active
August 9, 2024 18:42
-
-
Save amitsaha/5990310 to your computer and use it in GitHub Desktop.
Simple implementation of the tail command in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
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 file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" This is a more efficient version, since it does not read the entire | |
file | |
""" | |
import sys | |
import os | |
bufsize = 8192 | |
lines = int(sys.argv[1]) | |
fname = sys.argv[2] | |
fsize = os.stat(fname).st_size | |
iter = 0 | |
with open(sys.argv[2]) as f: | |
if bufsize > fsize: | |
bufsize = fsize-1 | |
data = [] | |
while True: | |
iter +=1 | |
f.seek(fsize-bufsize*iter) | |
data.extend(f.readlines()) | |
if len(data) >= lines or f.tell() == 0: | |
print(''.join(data[-lines:])) | |
break |
This is great, but you don't need the # -*- coding: utf-8 -*-
line in Python 3
Python 3.8 asyncio version,
#! /usr/bin/env python # -*- coding: utf-8 -*- ...
@therumbler TIL, thanks! I've been using the same "new file" template for years. Time to update!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Python 3.8 asyncio version,