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

Support for rich colored cell data #252

Closed smprather closed 12 months ago

smprather commented 1 year ago

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

I would like to have red/green colored PASS and FAIL elements in my table. I would like to use https://github.com/Textualize/rich markup. The coloring is working, but the column width detection is not filtering out terminal codes.

from rich import print as rprint
table = prettytable.PrettyTable(field_names=("Lib", "APL Type", "P/F"))

for lib in sorted(libs_to_publish):
    for apl_type in sorted(cfg.apl_types):
        success = Path(work_dir / lib / apl_type / "DONE").exists()
        table.add_row([lib, apl_type, "[green]PASS[white]" if success else "[red]FAIL[white]"])

rprint("[white]" + table.get_string())

image

Describe alternatives you've considered

I tried using a ColorTable thinking maybe you had term-control filtering (for width calculation) enabled in there. But that didn't work with rich.print. I got all kinds of term codes just printed to my terminal as if they weren't prefixed with the [ESC] character. image

Thanks!

hugovk commented 1 year ago

What's happening here, is you're passing things like "[green]PASS[white]" to PrettyTable, which are just strings. It's doing the width calculation based on that 18-char string.

Then you're fetching the rendered string representation of the whole table, and passing that to Rich.

Rich then converts the Rich-specific [x] codes into ANSI codes for printing, so "[green]PASS[white]" turns into a string with four visible characters, and ANSI codes on either side.

Some options:

smprather commented 12 months ago

I did some experimenting. I think rich.table.Table is the way to go. Thanks!