Created
April 8, 2016 16:15
-
-
Save colorstain/cbec84a08db8027ff99113454b600790 to your computer and use it in GitHub Desktop.
CLI helpers
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
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