import sys import threading import time import traceback class ConsoleTableColumn: def __init__(self, id, header: str, data_format=None, width=None): self.id = id self.header = header self.data_format = data_format self.width = width or len(header) class ConsoleTable: ESC = "\033[" def __init__(self, columns: list[ConsoleTableColumn], col_separator=" "): self.columns = columns self.col_separator = col_separator self.header_row = col_separator.join(map(lambda c: c.header, columns)) self._pending_data = None self._is_running = False def move_cursor(self, row, col): sys.stdout.write(f"{ConsoleTable.ESC}{row};{col}H") def clear_screen(self): sys.stdout.write(f"{ConsoleTable.ESC}2J") def hide_cursor(self): sys.stdout.write(f"{ConsoleTable.ESC}?25l") def show_cursor(self): sys.stdout.write(f"{ConsoleTable.ESC}?25h") def print_table(self, rows): print(self.header_row) print("-" * len(self.header_row)) for row in rows: cells = [] for col in self.columns: val = row[col.id] cell = f"{val:{col.data_format}}" if col.data_format else str(val) len_diff = col.width - len(cell) if len_diff > 0: cell += " " * len_diff else: leading_ws_count = 0 while ( leading_ws_count < -len_diff and cell[leading_ws_count] == " " ): leading_ws_count += 1 if leading_ws_count > 0: cell = cell[leading_ws_count:] len_diff = col.width - len(cell) if len_diff < 0: cell = cell[:len_diff] cells.append(cell) print(self.col_separator.join(cells)) def set_data(self, data): self._pending_data = data def run(self): try: self.clear_screen() self.hide_cursor() while self._is_running: if self._pending_data: # move to bottom of screen self.move_cursor(1, 1) self.print_table(self._pending_data) self._pending_data = None sys.stdout.flush() time.sleep(0.5) finally: self.show_cursor() def run_in_background(self): def run_wrapper(): self.run() self._is_running = True threading.Thread(target=run_wrapper, daemon=True) if __name__ == "__main__": cols = [ ConsoleTableColumn("symbol", f"{'Symbol':<10}"), ConsoleTableColumn("bid", f"{'Bid':>10}", data_format=">10"), ConsoleTableColumn("ask", f"{'Ask':>10}", data_format=">10"), ] bbo_data = [ {"symbol": "BTCUSDT", "bid": 104500.00, "ask": 105000.00}, {"symbol": "BNBUSDT", "bid": 645.00, "ask": 650.00}, ] try: table = ConsoleTable(cols) table.print_table(bbo_data) except Exception: traceback.print_exc()