Skip to content

Instantly share code, notes, and snippets.

@volker48
Last active October 9, 2015 04:18
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 volker48/3437288 to your computer and use it in GitHub Desktop.
Save volker48/3437288 to your computer and use it in GitHub Desktop.
Basic Python implementation of the unix tail command
#! /usr/bin/env python
'''
Copyright (c) 2012 Marcus McCurdy
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
Created 8/22/12
@author: Marcus McCurdy <marcus.mccurdy@gmail.com>
'''
import os, sys, argparse
def tail(path, lines_to_print=5):
if lines_to_print < 1:
return
with open(path, 'r') as file:
file.seek(-1, os.SEEK_END)
position = file.tell()
lines_seen = 0
if file.read(1) == '\n':
position -= 1
file.seek(position)
while lines_seen < lines_to_print and file.tell() > 0:
c = file.read(1)
if c == '\n':
lines_seen += 1
if lines_seen == lines_to_print:
break
position -= 2
file.seek(position)
sys.stdout.write(file.read())
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('path', help='The path to the file to tail')
parser.add_argument('-n', help='Print the last n lines of the file', type=int, default=5)
args = parser.parse_args()
tail(args.path, args.n)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment