-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdisplay_utils.py
62 lines (56 loc) · 2.24 KB
/
display_utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import sys
import math
class DynamicConsoleTable(object):
def __init__(self, layout):
self.layout = layout
self.header = '|'
self.divider = '|'
for i in range(len(layout)):
space = max(0, layout[i]['width'] - len(layout[i]['name']))
header_string = ' ' * int(space / 2.0) + layout[i]['name'] + ' ' * int(math.ceil(space / 2.0))
self.header += ' ' + header_string + ' |'
self.divider += '-' * (len(header_string) + 2) + '|'
self.updated = False
def _format_arg(self, arg, properties):
if arg == '':
return ' ' * max(len(properties['name']), properties['width'])
s = str(arg)
fixes = len(properties.get('prefix', '')) + len(properties.get('suffix', ''))
if properties.get('format', False):
s = properties['format'].format(arg)
elif isinstance(arg, float):
s = ('{:.' + str(max(0, properties['width'] - (len(str(int(arg))) + 1 + fixes))) + 'f}').format(arg)
if properties.get('prefix', False):
s = properties['prefix'] + s
if properties.get('suffix', False):
s += properties['suffix']
s = s[:properties['width']]
space = (max(len(properties['name']), properties['width']) - len(s))
if properties.get('align', None) == 'left':
return s + ' ' * space
elif properties.get('align', None) == 'center':
return ' ' * int(space / 2.0) + s + ' ' * int(math.ceil(space / 2.0))
else:
return ' ' * space + s
def print_header(self):
if self.updated:
self.finalize()
print self.divider
print self.header
print self.divider
def finalize(self):
if not self.updated:
self.update()
self.updated = False
print '\n' + self.divider
def update(self, *args):
self.updated = True
args = list(args)
while len(args) < len(self.layout):
args.append('')
row = '|'
for i in range(len(self.layout)):
formatted = self._format_arg(args[i], self.layout[i])
row += ' ' + formatted + ' |'
sys.stdout.write('\r' + row)
sys.stdout.flush()