Skip to content

Instantly share code, notes, and snippets.

@garyvdm
Last active August 29, 2015 13:58
Show Gist options
  • Save garyvdm/9970522 to your computer and use it in GitHub Desktop.
Save garyvdm/9970522 to your computer and use it in GitHub Desktop.
head and tail a stream
#!/usr/bin/env python
import argparse
import sys
import collections
parser = argparse.ArgumentParser(description='Show the first 10, and last 10 lines of a file.')
parser.add_argument('infile', nargs='?', default=sys.stdin,
help='Input file. Defauts to stdin if not provided.')
parser.add_argument('outfile', nargs='?', default=sys.stdout,
help='Output file. Defauts to stdout if not provided.')
parser.add_argument('--head-lines', '-n', type=int, default=10,
help='Number of head lines to display.')
parser.add_argument('--tail-lines', '-t', type=int, default=10,
help='Number of tail lines to display.')
args = parser.parse_args()
tail_lines = collections.deque([], args.tail_lines)
for i, l in enumerate(args.infile.readlines()):
if i < args.head_lines:
args.outfile.writelines([l])
else:
tail_lines.append(l)
args.outfile.writelines(tail_lines)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment