jazzband / prettytable

Display tabular data in a visually appealing ASCII table format
https://pypi.org/project/PrettyTable/
Other
1.35k stars 154 forks source link

Command line client? [feature request] #235

Open con-f-use opened 1 year ago

con-f-use commented 1 year ago

Is your feature request related to a problem? Please describe.

The column command in util-linux lacks a bunch of features that PrettyTable has. It is also not too cross-platform compatible.

Maybe PrettyTable sould define a console_script/project_script entry point and implement a CLI so we can have nice tables in shell scripts.

Describe the solution

Here is a simple version of what I mean:

# t.py
# Something like this but more elaborate should be part of PrettyTable

import prettytable, sys

def read_data(infile, sep=None):
    with (sys.stdin if infile == "-" else open(infile)) as fh:
        for x in fh:
            yield x.split(sep)

def make_table(data):
    table = prettytable.PrettyTable()
    table.field_names = next(data)

    for row in data:
        if len(row) != len(table.field_names):
            continue
        table.add_row(row)

    return table

def main(args=None, style=prettytable.SINGLE_BORDER):
    if args is None:
        args = sys.argv[1:]

    infile = args[0] if args else "-"
    data = read_data(infile)
    table = make_table(data)
    table.set_style(style)

    print(table)

if __name__ == "__main__":
    ret = main()
    raise SystemExit(ret)

In a final implementation, the python t.py call would of course be something like pretty-table --style msword_friednly --seperator '\t' --output-format json --input-format csv or something. But for my minimal example:

$ $ echo -e "a b c d\n1 2 3 4\n5 6 7 8\n" | python t.py
┌───┬───┬───┬───┐
│ a │ b │ c │ d │
├───┼───┼───┼───┤
│ 1 │ 2 │ 3 │ 4 │
│ 5 │ 6 │ 7 │ 8 │
└───┴───┴───┴───┘

Something like it could be part of PrettyTable and of course implement more options such as --separator '\t' or --style msword_friednly. The implimentation would like be a console_script entrypoint or project.scripts entry point.

If you think something like this might get merged, I might open a PR. Beforehand, there would be some questions, like for example which argument parser to use (click, argparse) or what the command's name should be.