Last active
August 29, 2015 13:58
-
-
Save garyvdm/9970522 to your computer and use it in GitHub Desktop.
head and tail a stream
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
#!/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