80 lines
3.0 KiB
Python
Executable File
80 lines
3.0 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""headtail — show the first and last N lines of a file together (context sandwich).
|
|
Usage: headtail [-n N] [--no-marker] [FILE]
|
|
head and tail in one view: the opening lines and the closing lines, with a
|
|
marker saying how many lines were skipped in the middle. For logs and outputs
|
|
where the beginning sets the scene and the end holds the verdict.
|
|
"""
|
|
import argparse, collections, sys
|
|
|
|
|
|
def head_tail(lines, n):
|
|
"""Return (shown_lines, skipped_count) for the first+last N sandwich."""
|
|
lines = list(lines)
|
|
if len(lines) <= 2 * n:
|
|
return lines, 0
|
|
return lines[:n] + lines[-n:], len(lines) - 2 * n
|
|
|
|
|
|
def main(argv=None):
|
|
ap = argparse.ArgumentParser(prog="headtail",
|
|
description="Show the first and last N lines of a file together (context sandwich).")
|
|
ap.add_argument("file", nargs="?", help="file to read (default: stdin)")
|
|
ap.add_argument("-n", "--lines", type=int, default=10, help="lines from each end (default 10)")
|
|
ap.add_argument("--no-marker", action="store_true", help="omit the '... skipped ...' marker line")
|
|
ap.add_argument("--selftest", action="store_true", help="run a built-in self-test and exit")
|
|
argv_list = list(argv) if argv is not None else sys.argv[1:]
|
|
if "--selftest" in argv_list:
|
|
return selftest()
|
|
a = ap.parse_args(argv)
|
|
if a.selftest:
|
|
return selftest()
|
|
if a.lines < 0:
|
|
print("headtail: -n must be >= 0", file=sys.stderr)
|
|
return 2
|
|
try:
|
|
if a.file:
|
|
with open(a.file, encoding="utf-8", errors="replace") as fh:
|
|
all_lines = fh.readlines()
|
|
else:
|
|
all_lines = sys.stdin.readlines()
|
|
except OSError as e:
|
|
print(f"headtail: {e}", file=sys.stderr)
|
|
return 1
|
|
shown, skipped = head_tail(all_lines, a.lines)
|
|
for i, line in enumerate(shown):
|
|
if skipped and not a.no_marker and a.lines > 0 and i == a.lines:
|
|
print(f"... [{skipped} line(s) omitted] ...")
|
|
sys.stdout.write(line if line.endswith("\n") else line + "\n")
|
|
return 0
|
|
|
|
|
|
def selftest():
|
|
lines = [f"line {i}\n" for i in range(1, 26)]
|
|
shown, skipped = head_tail(lines, 5)
|
|
assert len(shown) == 10 and skipped == 15, (len(shown), skipped)
|
|
assert shown[0] == "line 1\n" and shown[-1] == "line 25\n"
|
|
shown2, skipped2 = head_tail(lines[:8], 5)
|
|
assert skipped2 == 0 and len(shown2) == 8
|
|
import tempfile, os, io
|
|
from contextlib import redirect_stdout
|
|
with tempfile.NamedTemporaryFile("w", suffix=".txt", delete=False) as fh:
|
|
fh.writelines(lines)
|
|
path = fh.name
|
|
try:
|
|
buf = io.StringIO()
|
|
with redirect_stdout(buf):
|
|
rc = main(["-n", "3", path])
|
|
out = buf.getvalue()
|
|
assert rc == 0 and "line 1" in out and "line 25" in out, out
|
|
assert "[19 line(s) omitted]" in out, out
|
|
assert "line 12" not in out, out
|
|
finally:
|
|
os.unlink(path)
|
|
print("headtail selftest: PASS")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|