-
Notifications
You must be signed in to change notification settings - Fork 147
/
Copy pathprettify.py
83 lines (62 loc) · 2.15 KB
/
prettify.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import prettytable
import types
def tablify(data, table_border=True):
# TODO: Check that is prettytable-0.7.2 that supports the
# dynamic table columns number setting. Version 0.5 does not.
output = ''
# Empty outputs. False is probably a good output value
if data and not data:
output = ''
else:
table = prettytable.PrettyTable()
# List outputs.
if isinstance(data, (list, tuple)):
if len(data) > 0:
columns_num = 1
if isinstance(data[0], (list, tuple)):
columns_num = len(data[0])
for row in data:
if not row:
continue
if isinstance(row, (list, tuple)):
table.add_row(row)
else:
table.add_row([row])
# Dict outputs are display as tables
elif isinstance(data, types.DictType) and data:
# Populate the rows
randomitem = next(data.itervalues())
if isinstance(randomitem, (list, tuple)):
for field in data:
table.add_row([field] + data[field])
else:
for field in data:
table.add_row([field, str(data[field])])
# Else, try to stringify
else:
output = str(data)
if not output:
table.header = False
table.align = 'l'
table.border = table_border
output = table.get_string()
return output
def shorten(body, keep_header=0, keep_trailer=0):
"""
Smartly shorten a given string.
"""
# Cut header
if (keep_header
and not keep_trailer
and len(body) > keep_header):
return '..%s' % body[:keep_header]
# Cut footer
if (keep_trailer
and not keep_header
and len(body) > keep_trailer):
return '..%s' % body[-keep_header:]
if (keep_header
and keep_trailer
and len(body) > keep_header + keep_trailer):
return '%s .. %s' % (body[:keep_header], body[-keep_trailer:])
return body