File: pretty_table.py

package info (click to toggle)
python-bx 0.13.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 5,000 kB
  • sloc: python: 17,136; ansic: 2,326; makefile: 24; sh: 8
file content (41 lines) | stat: -rwxr-xr-x 929 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#!/usr/bin/python3

"""
Read some whitespace separated data from stdin and pretty print it so that
the columns line up.
"""

import sys


def main():
    pad = "\t"
    align = None
    if len(sys.argv) > 1:
        pad = " " * int(sys.argv[1])
    if len(sys.argv) > 2:
        align = sys.argv[2]
    rows = [line.split() for line in sys.stdin]
    print_tabular(rows, pad, align)


def print_tabular(rows, pad, align=None):
    if len(rows) == 0:
        return ""
    lengths = [len(col) for col in rows[0]]
    for row in rows[1:]:
        for i in range(0, len(row)):
            lengths[i] = max(lengths[i], len(row[i]))
    rval = ""
    for row in rows:
        rval = ""
        for i in range(0, len(row)):
            if align and align[i] == "l":
                rval += row[i].ljust(lengths[i])
            else:
                rval += row[i].rjust(lengths[i])
            rval += pad
        print(rval)


main()