Created
July 16, 2024 21:31
-
-
Save D4KU/72e8b8b4683d8ec1e93d33938f67845b to your computer and use it in GitHub Desktop.
Show and update a list of lists as a table in a terminal window
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import curses | |
| from time import sleep | |
| from os import get_terminal_size | |
| from functools import partial | |
| from itertools import cycle | |
| from random import random | |
| def display_rows(stdscr, getter, interval=10, timeout=0.1, pad=2, **kwargs): | |
| try: | |
| curses.curs_set(0) | |
| width, _ = get_terminal_size() | |
| q = width / interval * timeout | |
| for t in cycle(range(int(interval / timeout))): | |
| if t == 0: | |
| rows = getter(**kwargs) | |
| collens = [max(*map(len, map(str, x))) for x in zip(*rows)] | |
| joined = ((' ' * pad).join(str(cell).ljust(collen) for cell, collen in zip(row, collens)) | |
| for row in rows) | |
| stdscr.clear() | |
| for i, row in enumerate(joined, start=1): | |
| stdscr.addstr(i, 0, row) | |
| stdscr.addstr(0, 0, '-' * int(t * q)) | |
| stdscr.refresh() | |
| sleep(timeout) | |
| except KeyboardInterrupt: | |
| pass | |
| def update_rows(getter, **kwargs): | |
| return partial(display_rows, getter=getter, **kwargs) | |
| if __name__ == "__main__": | |
| def test_rows(): | |
| return (('abc', random()), ('d', random())) | |
| curses.wrapper(update_rows(test_rows)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment