Created
January 17, 2020 01:21
-
-
Save dmahugh/1c2912d560297e1b4da5b414d60d1b6d to your computer and use it in GitHub Desktop.
utility function to print a sqlite table to the console
This file contains 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 shutil | |
def print_table(*, cursor=None, table=None, title=None, rows=10): | |
"""Print contents of a table or cursor. | |
This is for quick printing of small data sets for diagnostic purposes, may | |
not work well with large numbers of columns. Takes a sqlite3 cursor and | |
table name as input. Output format and column widths is adjusted to fit | |
the current console line length as needed. | |
""" | |
if not cursor or not table: | |
raise ValueError("print_table requires cursor and table arguments.") | |
if not title: | |
title = f"{table} table" | |
cursor.execute(f"PRAGMA table_info({table})") | |
columns = [row[1] for row in cursor.fetchall()] | |
# default column width is the length of each column name | |
widths = [len(column) for column in columns] | |
# adjust column widths based on the data found in each column | |
cursor.execute(f"SELECT * FROM {table}") | |
cursor_rows = cursor.fetchall() | |
if cursor_rows: | |
for ncol, col_width in enumerate(widths): | |
max_data_width = max([len(str(row[ncol])) for row in cursor_rows[:rows]]) | |
widths[ncol] = max(col_width, max_data_width) | |
# all output lines will be truncated to console_width characters | |
console_width = shutil.get_terminal_size((80, 20))[0] - 1 | |
# print header rows | |
tot_width = min(sum(widths) + len(columns) - 1, console_width) | |
title_plus_rowcount = f"{title} ({len(cursor_rows)} rows)" | |
print("\n" + f" {title_plus_rowcount} ".center(tot_width, "-")) | |
column_headers = " ".join( | |
[column.ljust(width) for column, width in zip(columns, widths)] | |
) | |
print(column_headers[:console_width]) | |
underlines = " ".join([width * "-" for width in widths]) | |
print(underlines[:console_width]) | |
# print data rows | |
for row_number, row in enumerate(cursor_rows): | |
printed_row = " ".join( | |
[str(value).ljust(width) for value, width in zip(row, widths)] | |
) | |
print(printed_row[:console_width]) | |
if row_number >= rows - 1: | |
break |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment