Skip to content

Instantly share code, notes, and snippets.

@colorstain
Created April 8, 2016 16:15
Show Gist options
  • Save colorstain/cbec84a08db8027ff99113454b600790 to your computer and use it in GitHub Desktop.
Save colorstain/cbec84a08db8027ff99113454b600790 to your computer and use it in GitHub Desktop.
CLI helpers
def table(rows, add_index=False):
"""
Generates a table from a list of lists. The first row should contain the
headers.
"""
rows = [list(row) for row in rows]
headers = rows[0]
body = rows[1:]
if add_index:
headers.insert(0, '#')
body = [[i] + row for i, row in enumerate(body)]
# Determining the length of the columns
col_lens = []
for i in range(len(body[0])):
col_lens.append(len(str(max([x[i] for x in body] + headers[i:i+1],
key=lambda x: len(str(x))))))
formats = []
hformats = []
for i in range(len(body[0])):
col_len = col_lens[i]
if isinstance(rows[0][i], int):
# align right
formats.append('{{:>{}}}'.format(col_len))
else:
# align left
formats.append('{{:{}}}'.format(col_len))
hformats.append('{{:{}}}'.format(col_len))
pattern = ' | '.join(formats)
hpattern = ' | '.join(hformats)
separator = '-+-'.join('-' * n for n in col_lens)
output = []
output.append(hpattern.format(*headers))
output.append(separator)
for row in body:
output.append(pattern.format(*row))
return '\n'.join(output)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment