ATLAS Offline Software
Loading...
Searching...
No Matches
table_printer.py
Go to the documentation of this file.
1# Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
2"""
3Prints out a table, padded to make it pretty.
4
5call pprint_table with an output (e.g. sys.stdout, cStringIO, file)
6and table as a list of lists. Make sure table is "rectangular" -- each
7row has the same number of columns.
8
9MIT License
10
11Taken from:
12http://ginstrom.com/scribbles/2007/09/04/pretty-printing-a-table-in-python/
13
14Found with the google search "python print table" March 2010
15
16Minor modifications by <peter.waller@cern.ch> to include a "-" seperator for
17the header, and to change the number format code.
18
19"""
20
21__version__ = "0.1"
22__author__ = "Ryan Ginstrom"
23
24import sys
25
26from DQUtils.ext.thousands import splitThousands
27
28def format_num(num):
29 """Format a number according to given places.
30 Adds commas, etc."""
31 from builtins import int
32 if isinstance(num, int):
33 return splitThousands(num)
34
35 return str(num)
36
37def get_max_width(table, index):
38 """Get the maximum width of the given column index
39 """
40
41 return max([len(format_num(row[index])) for row in table])
42
43def pprint_table_to(out, table, header_loc=1):
44 """Prints out a table of data, padded for alignment
45
46 @param out: Output stream ("file-like object")
47 @param table: The table to print. A list of lists. Each row must have the same
48 number of columns.
49
50 """
51
52 col_paddings = []
53
54 for i in range(len(table[0])):
55 col_paddings.append(get_max_width(table, i))
56
57 for i, row in enumerate(table):
58 if i == header_loc:
59 print("-" * (sum(col_paddings) + (len(col_paddings)*3-1)), end='', file=out)
60 # left col
61 print(row[0].ljust(col_paddings[0] + 2), end='', file=out)
62 # rest of the cols
63 for i in range(1, len(row)):
64 col = format_num(row[i]).rjust(col_paddings[i] + 2)
65 print(col, end='', file=out)
66 print(file=out)
67
68def pprint_table(table, header_loc=1):
69 pprint_table_to(sys.stdout, table, header_loc)
70
71def pprint_table_string(table, header_loc=1):
72 from cStringIO import StringIO
73 sio = StringIO()
74 pprint_table_to(sio, table, header_loc)
75 return sio.getvalue()
76
77if __name__ == "__main__":
78 table = [["", "taste", "land speed", "life"],
79 ["spam", 300101, 4, 1003],
80 ["eggs", 105, 13, 42],
81 ["lumberjacks", 13, 105, 10]]
82
83 pprint_table(table)
void print(char *figname, TCanvas *c1)
#define max(a, b)
Definition cfImp.cxx:41
pprint_table_to(out, table, header_loc=1)
pprint_table(table, header_loc=1)
pprint_table_string(table, header_loc=1)
get_max_width(table, index)