Skip to content

Instantly share code, notes, and snippets.

@mguaypaq
Created May 14, 2024 15:12
Show Gist options
  • Save mguaypaq/71edee65b77bc007748e129b03b2070d to your computer and use it in GitHub Desktop.
Save mguaypaq/71edee65b77bc007748e129b03b2070d to your computer and use it in GitHub Desktop.
Command-line TSV viewer
#!/usr/bin/env python3
"""View a tsv in less with suitable tabstops"""
import itertools
from pathlib import Path
import os
def tabline(tsv: Path) -> str:
"""Compute a suitable tabline for `less --tabs`"""
max_widths = []
for line in tsv.open():
widths = [len(cell) for cell in line.split("\t")]
if len(widths) > len(max_widths):
max_widths.extend([0] * (len(widths) - len(max_widths)))
for i, w in enumerate(widths):
max_widths[i] = max(max_widths[i], w)
tab_stops = itertools.accumulate(w + 2 for w in max_widths)
return ",".join(map(str, tab_stops))
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("tsv", type=Path)
args = parser.parse_args()
os.execlp(
"less",
"less",
"--tabs",
tabline(args.tsv),
"--chop-long-lines",
"--",
str(args.tsv),
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment