prettytable 0.6.1__zip → 0.7.2__zip
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {prettytable-0.6.1 → prettytable-0.7.2}/CHANGELOG +28 -12
- {prettytable-0.6.1 → prettytable-0.7.2}/COPYING +3 -1
- {prettytable-0.6.1/prettytable.egg-info → prettytable-0.7.2}/PKG-INFO +3 -1
- {prettytable-0.6.1 → prettytable-0.7.2}/README +48 -12
- {prettytable-0.6.1 → prettytable-0.7.2/prettytable.egg-info}/PKG-INFO +3 -1
- {prettytable-0.6.1 → prettytable-0.7.2}/prettytable.py +590 -187
- {prettytable-0.6.1 → prettytable-0.7.2}/prettytable_test.py +173 -24
- {prettytable-0.6.1 → prettytable-0.7.2}/setup.py +2 -0
- {prettytable-0.6.1 → prettytable-0.7.2}/MANIFEST.in +0 -0
- {prettytable-0.6.1 → prettytable-0.7.2}/prettytable.egg-info/SOURCES.txt +0 -0
- {prettytable-0.6.1 → prettytable-0.7.2}/prettytable.egg-info/dependency_links.txt +0 -0
- {prettytable-0.6.1 → prettytable-0.7.2}/prettytable.egg-info/top_level.txt +0 -0
- {prettytable-0.6.1 → prettytable-0.7.2}/setup.cfg +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env python
|
|
2
2
|
#
|
|
3
|
-
# Copyright (c) 2009, Luke Maurits <luke@maurits.id.au>
|
|
3
|
+
# Copyright (c) 2009-2013, Luke Maurits <luke@maurits.id.au>
|
|
4
4
|
# All rights reserved.
|
|
5
5
|
# With contributions from:
|
|
6
6
|
# * Chris Clark
|
|
@@ -29,17 +29,31 @@
|
|
|
29
29
|
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
|
30
30
|
# POSSIBILITY OF SUCH DAMAGE.
|
|
31
31
|
|
|
32
|
-
__version__ = "0.
|
|
32
|
+
__version__ = "0.7.2"
|
|
33
33
|
|
|
34
|
-
import sys
|
|
35
34
|
import copy
|
|
35
|
+
import csv
|
|
36
36
|
import random
|
|
37
|
+
import re
|
|
38
|
+
import sys
|
|
37
39
|
import textwrap
|
|
40
|
+
import itertools
|
|
41
|
+
import unicodedata
|
|
38
42
|
|
|
39
43
|
py3k = sys.version_info[0] >= 3
|
|
40
44
|
if py3k:
|
|
41
45
|
unicode = str
|
|
42
46
|
basestring = str
|
|
47
|
+
itermap = map
|
|
48
|
+
iterzip = zip
|
|
49
|
+
uni_chr = chr
|
|
50
|
+
from html.parser import HTMLParser
|
|
51
|
+
else:
|
|
52
|
+
itermap = itertools.imap
|
|
53
|
+
iterzip = itertools.izip
|
|
54
|
+
uni_chr = unichr
|
|
55
|
+
from HTMLParser import HTMLParser
|
|
56
|
+
|
|
43
57
|
if py3k and sys.version_info[1] >= 2:
|
|
44
58
|
from html import escape
|
|
45
59
|
else:
|
|
@@ -49,6 +63,7 @@ else:
|
|
|
49
63
|
FRAME = 0
|
|
50
64
|
ALL = 1
|
|
51
65
|
NONE = 2
|
|
66
|
+
HEADER = 3
|
|
52
67
|
|
|
53
68
|
# Table styles
|
|
54
69
|
DEFAULT = 10
|
|
@@ -56,43 +71,34 @@ MSWORD_FRIENDLY = 11
|
|
|
56
71
|
PLAIN_COLUMNS = 12
|
|
57
72
|
RANDOM = 20
|
|
58
73
|
|
|
74
|
+
_re = re.compile("\033\[[0-9;]*m")
|
|
75
|
+
|
|
59
76
|
def _get_size(text):
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
max_height += 1
|
|
65
|
-
if len(line) > max_width:
|
|
66
|
-
max_width = len(line)
|
|
67
|
-
|
|
68
|
-
return (max_width, max_height)
|
|
77
|
+
lines = text.split("\n")
|
|
78
|
+
height = len(lines)
|
|
79
|
+
width = max([_str_block_width(line) for line in lines])
|
|
80
|
+
return (width, height)
|
|
69
81
|
|
|
70
|
-
def _unicode(value, encoding="UTF-8"):
|
|
71
|
-
if not isinstance(value, basestring):
|
|
72
|
-
value = str(value)
|
|
73
|
-
if not isinstance(value, unicode):
|
|
74
|
-
value = unicode(value, encoding, "replace")
|
|
75
|
-
return value
|
|
76
|
-
|
|
77
82
|
class PrettyTable(object):
|
|
78
83
|
|
|
79
|
-
def __init__(self, field_names=None,
|
|
84
|
+
def __init__(self, field_names=None, **kwargs):
|
|
80
85
|
|
|
81
86
|
"""Return a new PrettyTable instance
|
|
82
87
|
|
|
83
88
|
Arguments:
|
|
84
89
|
|
|
90
|
+
encoding - Unicode encoding scheme used to decode any encoded input
|
|
85
91
|
field_names - list or tuple of field names
|
|
86
|
-
encoding - Unicode encoding scheme to use
|
|
87
92
|
fields - list or tuple of field names to include in displays
|
|
88
93
|
start - index of first data row to include in output
|
|
89
94
|
end - index of last data row to include in output PLUS ONE (list slice style)
|
|
90
|
-
fields - names of fields (columns) to include
|
|
91
95
|
header - print a header showing field names (True or False)
|
|
96
|
+
header_style - stylisation to apply to field names in header ("cap", "title", "upper", "lower" or None)
|
|
92
97
|
border - print a border around the table (True or False)
|
|
93
|
-
hrules - controls printing of horizontal rules after rows. Allowed values: FRAME, ALL, NONE
|
|
94
|
-
|
|
95
|
-
|
|
98
|
+
hrules - controls printing of horizontal rules after rows. Allowed values: FRAME, HEADER, ALL, NONE
|
|
99
|
+
vrules - controls printing of vertical rules between columns. Allowed values: FRAME, ALL, NONE
|
|
100
|
+
int_format - controls formatting of integer data
|
|
101
|
+
float_format - controls formatting of floating point data
|
|
96
102
|
padding_width - number of spaces on either side of column data (only used if left and right paddings are None)
|
|
97
103
|
left_padding_width - number of spaces on left hand side of column data
|
|
98
104
|
right_padding_width - number of spaces on right hand side of column data
|
|
@@ -101,57 +107,101 @@ class PrettyTable(object):
|
|
|
101
107
|
junction_char - single character string used to draw line junctions
|
|
102
108
|
sortby - name of field to sort rows by
|
|
103
109
|
sort_key - sorting key function, applied to data points before sorting
|
|
110
|
+
valign - default valign for each row (None, "t", "m" or "b")
|
|
104
111
|
reversesort - True or False to sort in descending or ascending order"""
|
|
105
112
|
|
|
106
|
-
self.encoding = encoding
|
|
113
|
+
self.encoding = kwargs.get("encoding", "UTF-8")
|
|
107
114
|
|
|
108
115
|
# Data
|
|
109
116
|
self._field_names = []
|
|
110
117
|
self._align = {}
|
|
118
|
+
self._valign = {}
|
|
111
119
|
self._max_width = {}
|
|
112
120
|
self._rows = []
|
|
113
121
|
if field_names:
|
|
114
122
|
self.field_names = field_names
|
|
115
123
|
else:
|
|
116
124
|
self._widths = []
|
|
117
|
-
self._rows = []
|
|
118
125
|
|
|
119
126
|
# Options
|
|
120
|
-
self._options = "start end fields header border sortby reversesort sort_key attributes format hrules".split()
|
|
127
|
+
self._options = "start end fields header border sortby reversesort sort_key attributes format hrules vrules".split()
|
|
121
128
|
self._options.extend("int_format float_format padding_width left_padding_width right_padding_width".split())
|
|
122
|
-
self._options.extend("vertical_char horizontal_char junction_char".split())
|
|
129
|
+
self._options.extend("vertical_char horizontal_char junction_char header_style valign xhtml print_empty".split())
|
|
123
130
|
for option in self._options:
|
|
124
131
|
if option in kwargs:
|
|
125
132
|
self._validate_option(option, kwargs[option])
|
|
126
133
|
else:
|
|
127
134
|
kwargs[option] = None
|
|
128
135
|
|
|
129
|
-
|
|
130
136
|
self._start = kwargs["start"] or 0
|
|
131
137
|
self._end = kwargs["end"] or None
|
|
132
138
|
self._fields = kwargs["fields"] or None
|
|
133
139
|
|
|
134
|
-
|
|
135
|
-
|
|
140
|
+
if kwargs["header"] in (True, False):
|
|
141
|
+
self._header = kwargs["header"]
|
|
142
|
+
else:
|
|
143
|
+
self._header = True
|
|
144
|
+
self._header_style = kwargs["header_style"] or None
|
|
145
|
+
if kwargs["border"] in (True, False):
|
|
146
|
+
self._border = kwargs["border"]
|
|
147
|
+
else:
|
|
148
|
+
self._border = True
|
|
136
149
|
self._hrules = kwargs["hrules"] or FRAME
|
|
150
|
+
self._vrules = kwargs["vrules"] or ALL
|
|
137
151
|
|
|
138
152
|
self._sortby = kwargs["sortby"] or None
|
|
139
|
-
|
|
153
|
+
if kwargs["reversesort"] in (True, False):
|
|
154
|
+
self._reversesort = kwargs["reversesort"]
|
|
155
|
+
else:
|
|
156
|
+
self._reversesort = False
|
|
140
157
|
self._sort_key = kwargs["sort_key"] or (lambda x: x)
|
|
141
158
|
|
|
142
|
-
self._int_format = kwargs["
|
|
159
|
+
self._int_format = kwargs["int_format"] or {}
|
|
143
160
|
self._float_format = kwargs["float_format"] or {}
|
|
144
161
|
self._padding_width = kwargs["padding_width"] or 1
|
|
145
162
|
self._left_padding_width = kwargs["left_padding_width"] or None
|
|
146
163
|
self._right_padding_width = kwargs["right_padding_width"] or None
|
|
147
164
|
|
|
148
|
-
self._vertical_char = kwargs["vertical_char"] or "|"
|
|
149
|
-
self._horizontal_char = kwargs["horizontal_char"] or "-"
|
|
150
|
-
self._junction_char = kwargs["junction_char"] or "+"
|
|
165
|
+
self._vertical_char = kwargs["vertical_char"] or self._unicode("|")
|
|
166
|
+
self._horizontal_char = kwargs["horizontal_char"] or self._unicode("-")
|
|
167
|
+
self._junction_char = kwargs["junction_char"] or self._unicode("+")
|
|
151
168
|
|
|
169
|
+
if kwargs["print_empty"] in (True, False):
|
|
170
|
+
self._print_empty = kwargs["print_empty"]
|
|
171
|
+
else:
|
|
172
|
+
self._print_empty = True
|
|
152
173
|
self._format = kwargs["format"] or False
|
|
174
|
+
self._xhtml = kwargs["xhtml"] or False
|
|
153
175
|
self._attributes = kwargs["attributes"] or {}
|
|
154
176
|
|
|
177
|
+
def _unicode(self, value):
|
|
178
|
+
if not isinstance(value, basestring):
|
|
179
|
+
value = str(value)
|
|
180
|
+
if not isinstance(value, unicode):
|
|
181
|
+
value = unicode(value, self.encoding, "strict")
|
|
182
|
+
return value
|
|
183
|
+
|
|
184
|
+
def _justify(self, text, width, align):
|
|
185
|
+
excess = width - _str_block_width(text)
|
|
186
|
+
if align == "l":
|
|
187
|
+
return text + excess * " "
|
|
188
|
+
elif align == "r":
|
|
189
|
+
return excess * " " + text
|
|
190
|
+
else:
|
|
191
|
+
if excess % 2:
|
|
192
|
+
# Uneven padding
|
|
193
|
+
# Put more space on right if text is of odd length...
|
|
194
|
+
if _str_block_width(text) % 2:
|
|
195
|
+
return (excess//2)*" " + text + (excess//2 + 1)*" "
|
|
196
|
+
# and more space on left if text is of even length
|
|
197
|
+
else:
|
|
198
|
+
return (excess//2 + 1)*" " + text + (excess//2)*" "
|
|
199
|
+
# Why distribute extra space this way? To match the behaviour of
|
|
200
|
+
# the inbuilt str.center() method.
|
|
201
|
+
else:
|
|
202
|
+
# Equal padding on either side
|
|
203
|
+
return (excess//2)*" " + text + (excess//2)*" "
|
|
204
|
+
|
|
155
205
|
def __getattr__(self, name):
|
|
156
206
|
|
|
157
207
|
if name == "rowcount":
|
|
@@ -168,20 +218,26 @@ class PrettyTable(object):
|
|
|
168
218
|
|
|
169
219
|
def __getitem__(self, index):
|
|
170
220
|
|
|
171
|
-
|
|
221
|
+
new = PrettyTable()
|
|
222
|
+
new.field_names = self.field_names
|
|
223
|
+
for attr in self._options:
|
|
224
|
+
setattr(new, "_"+attr, getattr(self, "_"+attr))
|
|
225
|
+
setattr(new, "_align", getattr(self, "_align"))
|
|
172
226
|
if isinstance(index, slice):
|
|
173
|
-
|
|
227
|
+
for row in self._rows[index]:
|
|
228
|
+
new.add_row(row)
|
|
174
229
|
elif isinstance(index, int):
|
|
175
|
-
|
|
230
|
+
new.add_row(self._rows[index])
|
|
176
231
|
else:
|
|
177
232
|
raise Exception("Index %s is invalid, must be an integer or slice" % str(index))
|
|
178
|
-
return
|
|
233
|
+
return new
|
|
179
234
|
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
235
|
+
if py3k:
|
|
236
|
+
def __str__(self):
|
|
237
|
+
return self.__unicode__()
|
|
238
|
+
else:
|
|
239
|
+
def __str__(self):
|
|
240
|
+
return self.__unicode__().encode(self.encoding)
|
|
185
241
|
|
|
186
242
|
def __unicode__(self):
|
|
187
243
|
return self.get_string()
|
|
@@ -198,7 +254,9 @@ class PrettyTable(object):
|
|
|
198
254
|
# Secondly, in the _get_options method, where keyword arguments are mixed with persistent settings
|
|
199
255
|
|
|
200
256
|
def _validate_option(self, option, val):
|
|
201
|
-
if option in ("
|
|
257
|
+
if option in ("field_names"):
|
|
258
|
+
self._validate_field_names(val)
|
|
259
|
+
elif option in ("start", "end", "max_width", "padding_width", "left_padding_width", "right_padding_width", "format"):
|
|
202
260
|
self._validate_nonnegative_int(option, val)
|
|
203
261
|
elif option in ("sortby"):
|
|
204
262
|
self._validate_field_name(option, val)
|
|
@@ -206,10 +264,14 @@ class PrettyTable(object):
|
|
|
206
264
|
self._validate_function(option, val)
|
|
207
265
|
elif option in ("hrules"):
|
|
208
266
|
self._validate_hrules(option, val)
|
|
267
|
+
elif option in ("vrules"):
|
|
268
|
+
self._validate_vrules(option, val)
|
|
209
269
|
elif option in ("fields"):
|
|
210
270
|
self._validate_all_field_names(option, val)
|
|
211
|
-
elif option in ("header", "border", "reversesort"):
|
|
271
|
+
elif option in ("header", "border", "reversesort", "xhtml", "print_empty"):
|
|
212
272
|
self._validate_true_or_false(option, val)
|
|
273
|
+
elif option in ("header_style"):
|
|
274
|
+
self._validate_header_style(val)
|
|
213
275
|
elif option in ("int_format"):
|
|
214
276
|
self._validate_int_format(option, val)
|
|
215
277
|
elif option in ("float_format"):
|
|
@@ -221,17 +283,47 @@ class PrettyTable(object):
|
|
|
221
283
|
else:
|
|
222
284
|
raise Exception("Unrecognised option: %s!" % option)
|
|
223
285
|
|
|
286
|
+
def _validate_field_names(self, val):
|
|
287
|
+
# Check for appropriate length
|
|
288
|
+
if self._field_names:
|
|
289
|
+
try:
|
|
290
|
+
assert len(val) == len(self._field_names)
|
|
291
|
+
except AssertionError:
|
|
292
|
+
raise Exception("Field name list has incorrect number of values, (actual) %d!=%d (expected)" % (len(val), len(self._field_names)))
|
|
293
|
+
if self._rows:
|
|
294
|
+
try:
|
|
295
|
+
assert len(val) == len(self._rows[0])
|
|
296
|
+
except AssertionError:
|
|
297
|
+
raise Exception("Field name list has incorrect number of values, (actual) %d!=%d (expected)" % (len(val), len(self._rows[0])))
|
|
298
|
+
# Check for uniqueness
|
|
299
|
+
try:
|
|
300
|
+
assert len(val) == len(set(val))
|
|
301
|
+
except AssertionError:
|
|
302
|
+
raise Exception("Field names must be unique!")
|
|
303
|
+
|
|
304
|
+
def _validate_header_style(self, val):
|
|
305
|
+
try:
|
|
306
|
+
assert val in ("cap", "title", "upper", "lower", None)
|
|
307
|
+
except AssertionError:
|
|
308
|
+
raise Exception("Invalid header style, use cap, title, upper, lower or None!")
|
|
309
|
+
|
|
224
310
|
def _validate_align(self, val):
|
|
225
311
|
try:
|
|
226
312
|
assert val in ["l","c","r"]
|
|
227
313
|
except AssertionError:
|
|
228
314
|
raise Exception("Alignment %s is invalid, use l, c or r!" % val)
|
|
229
315
|
|
|
316
|
+
def _validate_valign(self, val):
|
|
317
|
+
try:
|
|
318
|
+
assert val in ["t","m","b",None]
|
|
319
|
+
except AssertionError:
|
|
320
|
+
raise Exception("Alignment %s is invalid, use t, m, b or None!" % val)
|
|
321
|
+
|
|
230
322
|
def _validate_nonnegative_int(self, name, val):
|
|
231
323
|
try:
|
|
232
324
|
assert int(val) >= 0
|
|
233
325
|
except AssertionError:
|
|
234
|
-
raise Exception("Invalid value for %s: %s!" % (name, _unicode(val)))
|
|
326
|
+
raise Exception("Invalid value for %s: %s!" % (name, self._unicode(val)))
|
|
235
327
|
|
|
236
328
|
def _validate_true_or_false(self, name, val):
|
|
237
329
|
try:
|
|
@@ -268,14 +360,20 @@ class PrettyTable(object):
|
|
|
268
360
|
raise Exception("Invalid value for %s! Must be a function." % name)
|
|
269
361
|
|
|
270
362
|
def _validate_hrules(self, name, val):
|
|
363
|
+
try:
|
|
364
|
+
assert val in (ALL, FRAME, HEADER, NONE)
|
|
365
|
+
except AssertionError:
|
|
366
|
+
raise Exception("Invalid value for %s! Must be ALL, FRAME, HEADER or NONE." % name)
|
|
367
|
+
|
|
368
|
+
def _validate_vrules(self, name, val):
|
|
271
369
|
try:
|
|
272
370
|
assert val in (ALL, FRAME, NONE)
|
|
273
371
|
except AssertionError:
|
|
274
|
-
raise Exception("Invalid value for %s! Must be ALL, FRAME or NONE." % name)
|
|
372
|
+
raise Exception("Invalid value for %s! Must be ALL, FRAME, or NONE." % name)
|
|
275
373
|
|
|
276
374
|
def _validate_field_name(self, name, val):
|
|
277
375
|
try:
|
|
278
|
-
assert val in self._field_names
|
|
376
|
+
assert (val in self._field_names) or (val is None)
|
|
279
377
|
except AssertionError:
|
|
280
378
|
raise Exception("Invalid field name: %s!" % val)
|
|
281
379
|
|
|
@@ -288,7 +386,7 @@ class PrettyTable(object):
|
|
|
288
386
|
|
|
289
387
|
def _validate_single_char(self, name, val):
|
|
290
388
|
try:
|
|
291
|
-
assert
|
|
389
|
+
assert _str_block_width(val) == 1
|
|
292
390
|
except AssertionError:
|
|
293
391
|
raise Exception("Invalid value for %s! Must be a string of length 1." % name)
|
|
294
392
|
|
|
@@ -310,6 +408,8 @@ class PrettyTable(object):
|
|
|
310
408
|
|
|
311
409
|
fields - list or tuple of field names"""
|
|
312
410
|
def _set_field_names(self, val):
|
|
411
|
+
val = [self._unicode(x) for x in val]
|
|
412
|
+
self._validate_option("field_names", val)
|
|
313
413
|
if self._field_names:
|
|
314
414
|
old_names = self._field_names[:]
|
|
315
415
|
self._field_names = val
|
|
@@ -317,10 +417,20 @@ class PrettyTable(object):
|
|
|
317
417
|
for old_name, new_name in zip(old_names, val):
|
|
318
418
|
self._align[new_name] = self._align[old_name]
|
|
319
419
|
for old_name in old_names:
|
|
320
|
-
self._align
|
|
420
|
+
if old_name not in self._align:
|
|
421
|
+
self._align.pop(old_name)
|
|
321
422
|
else:
|
|
322
423
|
for field in self._field_names:
|
|
323
424
|
self._align[field] = "c"
|
|
425
|
+
if self._valign and old_names:
|
|
426
|
+
for old_name, new_name in zip(old_names, val):
|
|
427
|
+
self._valign[new_name] = self._valign[old_name]
|
|
428
|
+
for old_name in old_names:
|
|
429
|
+
if old_name not in self._valign:
|
|
430
|
+
self._valign.pop(old_name)
|
|
431
|
+
else:
|
|
432
|
+
for field in self._field_names:
|
|
433
|
+
self._valign[field] = "t"
|
|
324
434
|
field_names = property(_get_field_names, _set_field_names)
|
|
325
435
|
|
|
326
436
|
def _get_align(self):
|
|
@@ -331,14 +441,34 @@ class PrettyTable(object):
|
|
|
331
441
|
self._align[field] = val
|
|
332
442
|
align = property(_get_align, _set_align)
|
|
333
443
|
|
|
444
|
+
def _get_valign(self):
|
|
445
|
+
return self._valign
|
|
446
|
+
def _set_valign(self, val):
|
|
447
|
+
self._validate_valign(val)
|
|
448
|
+
for field in self._field_names:
|
|
449
|
+
self._valign[field] = val
|
|
450
|
+
valign = property(_get_valign, _set_valign)
|
|
451
|
+
|
|
334
452
|
def _get_max_width(self):
|
|
335
453
|
return self._max_width
|
|
336
454
|
def _set_max_width(self, val):
|
|
337
|
-
self.
|
|
455
|
+
self._validate_option("max_width", val)
|
|
338
456
|
for field in self._field_names:
|
|
339
457
|
self._max_width[field] = val
|
|
340
458
|
max_width = property(_get_max_width, _set_max_width)
|
|
341
459
|
|
|
460
|
+
def _get_fields(self):
|
|
461
|
+
"""List or tuple of field names to include in displays
|
|
462
|
+
|
|
463
|
+
Arguments:
|
|
464
|
+
|
|
465
|
+
fields - list or tuple of field names to include in displays"""
|
|
466
|
+
return self._fields
|
|
467
|
+
def _set_fields(self, val):
|
|
468
|
+
self._validate_option("fields", val)
|
|
469
|
+
self._fields = val
|
|
470
|
+
fields = property(_get_fields, _set_fields)
|
|
471
|
+
|
|
342
472
|
def _get_start(self):
|
|
343
473
|
"""Start index of the range of rows to print
|
|
344
474
|
|
|
@@ -412,6 +542,18 @@ class PrettyTable(object):
|
|
|
412
542
|
self._header = val
|
|
413
543
|
header = property(_get_header, _set_header)
|
|
414
544
|
|
|
545
|
+
def _get_header_style(self):
|
|
546
|
+
"""Controls stylisation applied to field names in header
|
|
547
|
+
|
|
548
|
+
Arguments:
|
|
549
|
+
|
|
550
|
+
header_style - stylisation to apply to field names in header ("cap", "title", "upper", "lower" or None)"""
|
|
551
|
+
return self._header_style
|
|
552
|
+
def _set_header_style(self, val):
|
|
553
|
+
self._validate_header_style(val)
|
|
554
|
+
self._header_style = val
|
|
555
|
+
header_style = property(_get_header_style, _set_header_style)
|
|
556
|
+
|
|
415
557
|
def _get_border(self):
|
|
416
558
|
"""Controls printing of border around table
|
|
417
559
|
|
|
@@ -429,13 +571,25 @@ class PrettyTable(object):
|
|
|
429
571
|
|
|
430
572
|
Arguments:
|
|
431
573
|
|
|
432
|
-
hrules - horizontal rules style. Allowed values: FRAME, ALL, NONE"""
|
|
574
|
+
hrules - horizontal rules style. Allowed values: FRAME, ALL, HEADER, NONE"""
|
|
433
575
|
return self._hrules
|
|
434
576
|
def _set_hrules(self, val):
|
|
435
577
|
self._validate_option("hrules", val)
|
|
436
578
|
self._hrules = val
|
|
437
579
|
hrules = property(_get_hrules, _set_hrules)
|
|
438
580
|
|
|
581
|
+
def _get_vrules(self):
|
|
582
|
+
"""Controls printing of vertical rules between columns
|
|
583
|
+
|
|
584
|
+
Arguments:
|
|
585
|
+
|
|
586
|
+
vrules - vertical rules style. Allowed values: FRAME, ALL, NONE"""
|
|
587
|
+
return self._vrules
|
|
588
|
+
def _set_vrules(self, val):
|
|
589
|
+
self._validate_option("vrules", val)
|
|
590
|
+
self._vrules = val
|
|
591
|
+
vrules = property(_get_vrules, _set_vrules)
|
|
592
|
+
|
|
439
593
|
def _get_int_format(self):
|
|
440
594
|
"""Controls formatting of integer data
|
|
441
595
|
Arguments:
|
|
@@ -443,7 +597,7 @@ class PrettyTable(object):
|
|
|
443
597
|
int_format - integer format string"""
|
|
444
598
|
return self._int_format
|
|
445
599
|
def _set_int_format(self, val):
|
|
446
|
-
self._validate_option("int_format", val)
|
|
600
|
+
# self._validate_option("int_format", val)
|
|
447
601
|
for field in self._field_names:
|
|
448
602
|
self._int_format[field] = val
|
|
449
603
|
int_format = property(_get_int_format, _set_int_format)
|
|
@@ -455,7 +609,7 @@ class PrettyTable(object):
|
|
|
455
609
|
float_format - floating point format string"""
|
|
456
610
|
return self._float_format
|
|
457
611
|
def _set_float_format(self, val):
|
|
458
|
-
self._validate_option("float_format", val)
|
|
612
|
+
# self._validate_option("float_format", val)
|
|
459
613
|
for field in self._field_names:
|
|
460
614
|
self._float_format[field] = val
|
|
461
615
|
float_format = property(_get_float_format, _set_float_format)
|
|
@@ -504,6 +658,7 @@ class PrettyTable(object):
|
|
|
504
658
|
vertical_char - single character string used to draw vertical lines"""
|
|
505
659
|
return self._vertical_char
|
|
506
660
|
def _set_vertical_char(self, val):
|
|
661
|
+
val = self._unicode(val)
|
|
507
662
|
self._validate_option("vertical_char", val)
|
|
508
663
|
self._vertical_char = val
|
|
509
664
|
vertical_char = property(_get_vertical_char, _set_vertical_char)
|
|
@@ -516,6 +671,7 @@ class PrettyTable(object):
|
|
|
516
671
|
horizontal_char - single character string used to draw horizontal lines"""
|
|
517
672
|
return self._horizontal_char
|
|
518
673
|
def _set_horizontal_char(self, val):
|
|
674
|
+
val = self._unicode(val)
|
|
519
675
|
self._validate_option("horizontal_char", val)
|
|
520
676
|
self._horizontal_char = val
|
|
521
677
|
horizontal_char = property(_get_horizontal_char, _set_horizontal_char)
|
|
@@ -528,6 +684,7 @@ class PrettyTable(object):
|
|
|
528
684
|
junction_char - single character string used to draw line junctions"""
|
|
529
685
|
return self._junction_char
|
|
530
686
|
def _set_junction_char(self, val):
|
|
687
|
+
val = self._unicode(val)
|
|
531
688
|
self._validate_option("vertical_char", val)
|
|
532
689
|
self._junction_char = val
|
|
533
690
|
junction_char = property(_get_junction_char, _set_junction_char)
|
|
@@ -544,6 +701,18 @@ class PrettyTable(object):
|
|
|
544
701
|
self._format = val
|
|
545
702
|
format = property(_get_format, _set_format)
|
|
546
703
|
|
|
704
|
+
def _get_print_empty(self):
|
|
705
|
+
"""Controls whether or not empty tables produce a header and frame or just an empty string
|
|
706
|
+
|
|
707
|
+
Arguments:
|
|
708
|
+
|
|
709
|
+
print_empty - True or False"""
|
|
710
|
+
return self._print_empty
|
|
711
|
+
def _set_print_empty(self, val):
|
|
712
|
+
self._validate_option("print_empty", val)
|
|
713
|
+
self._print_empty = val
|
|
714
|
+
print_empty = property(_get_print_empty, _set_print_empty)
|
|
715
|
+
|
|
547
716
|
def _get_attributes(self):
|
|
548
717
|
"""A dictionary of HTML attribute name/value pairs to be included in the <table> tag when printing HTML
|
|
549
718
|
|
|
@@ -552,7 +721,7 @@ class PrettyTable(object):
|
|
|
552
721
|
attributes - dictionary of attributes"""
|
|
553
722
|
return self._attributes
|
|
554
723
|
def _set_attributes(self, val):
|
|
555
|
-
self.
|
|
724
|
+
self._validate_option("attributes", val)
|
|
556
725
|
self._attributes = val
|
|
557
726
|
attributes = property(_get_attributes, _set_attributes)
|
|
558
727
|
|
|
@@ -593,6 +762,7 @@ class PrettyTable(object):
|
|
|
593
762
|
self.header = True
|
|
594
763
|
self.border = True
|
|
595
764
|
self._hrules = FRAME
|
|
765
|
+
self._vrules = ALL
|
|
596
766
|
self.padding_width = 1
|
|
597
767
|
self.left_padding_width = 1
|
|
598
768
|
self.right_padding_width = 1
|
|
@@ -623,7 +793,8 @@ class PrettyTable(object):
|
|
|
623
793
|
# Just for fun!
|
|
624
794
|
self.header = random.choice((True, False))
|
|
625
795
|
self.border = random.choice((True, False))
|
|
626
|
-
self._hrules = random.choice((ALL, FRAME, NONE))
|
|
796
|
+
self._hrules = random.choice((ALL, FRAME, HEADER, NONE))
|
|
797
|
+
self._vrules = random.choice((ALL, FRAME, NONE))
|
|
627
798
|
self.left_padding_width = random.randint(0,5)
|
|
628
799
|
self.right_padding_width = random.randint(0,5)
|
|
629
800
|
self.vertical_char = random.choice("~!@#$%^&*()_+|-=\{}[];':\",./;<>?")
|
|
@@ -645,6 +816,8 @@ class PrettyTable(object):
|
|
|
645
816
|
|
|
646
817
|
if self._field_names and len(row) != len(self._field_names):
|
|
647
818
|
raise Exception("Row has incorrect number of values, (actual) %d!=%d (expected)" %(len(row),len(self._field_names)))
|
|
819
|
+
if not self._field_names:
|
|
820
|
+
self.field_names = [("Field %d" % (n+1)) for n in range(0,len(row))]
|
|
648
821
|
self._rows.append(list(row))
|
|
649
822
|
|
|
650
823
|
def del_row(self, row_index):
|
|
@@ -659,7 +832,7 @@ class PrettyTable(object):
|
|
|
659
832
|
raise Exception("Cant delete row at index %d, table only has %d rows!" % (row_index, len(self._rows)))
|
|
660
833
|
del self._rows[row_index]
|
|
661
834
|
|
|
662
|
-
def add_column(self, fieldname, column, align="c"):
|
|
835
|
+
def add_column(self, fieldname, column, align="c", valign="t"):
|
|
663
836
|
|
|
664
837
|
"""Add a column to the table.
|
|
665
838
|
|
|
@@ -668,12 +841,15 @@ class PrettyTable(object):
|
|
|
668
841
|
fieldname - name of the field to contain the new column of data
|
|
669
842
|
column - column of data, should be a list with as many elements as the
|
|
670
843
|
table has rows
|
|
671
|
-
align - desired alignment for this column - "l" for left, "c" for centre and "r" for right
|
|
844
|
+
align - desired alignment for this column - "l" for left, "c" for centre and "r" for right
|
|
845
|
+
valign - desired vertical alignment for new columns - "t" for top, "m" for middle and "b" for bottom"""
|
|
672
846
|
|
|
673
847
|
if len(self._rows) in (0, len(column)):
|
|
674
848
|
self._validate_align(align)
|
|
849
|
+
self._validate_valign(valign)
|
|
675
850
|
self._field_names.append(fieldname)
|
|
676
851
|
self._align[fieldname] = align
|
|
852
|
+
self._valign[fieldname] = valign
|
|
677
853
|
for i in range(0, len(column)):
|
|
678
854
|
if len(self._rows) < i+1:
|
|
679
855
|
self._rows.append([])
|
|
@@ -708,10 +884,10 @@ class PrettyTable(object):
|
|
|
708
884
|
|
|
709
885
|
def _format_value(self, field, value):
|
|
710
886
|
if isinstance(value, int) and field in self._int_format:
|
|
711
|
-
value = ("%%%sd" % self._int_format[field]) % value
|
|
887
|
+
value = self._unicode(("%%%sd" % self._int_format[field]) % value)
|
|
712
888
|
elif isinstance(value, float) and field in self._float_format:
|
|
713
|
-
value = ("%%%sf" % self._float_format[field]) % value
|
|
714
|
-
return value
|
|
889
|
+
value = self._unicode(("%%%sf" % self._float_format[field]) % value)
|
|
890
|
+
return self._unicode(value)
|
|
715
891
|
|
|
716
892
|
def _compute_widths(self, rows, options):
|
|
717
893
|
if options["header"]:
|
|
@@ -720,8 +896,11 @@ class PrettyTable(object):
|
|
|
720
896
|
widths = len(self.field_names) * [0]
|
|
721
897
|
for row in rows:
|
|
722
898
|
for index, value in enumerate(row):
|
|
723
|
-
|
|
724
|
-
|
|
899
|
+
fieldname = self.field_names[index]
|
|
900
|
+
if fieldname in self.max_width:
|
|
901
|
+
widths[index] = max(widths[index], min(_get_size(value)[0], self.max_width[fieldname]))
|
|
902
|
+
else:
|
|
903
|
+
widths[index] = max(widths[index], _get_size(value)[0])
|
|
725
904
|
self._widths = widths
|
|
726
905
|
|
|
727
906
|
def _get_padding_widths(self, options):
|
|
@@ -743,7 +922,7 @@ class PrettyTable(object):
|
|
|
743
922
|
|
|
744
923
|
options - dictionary of option settings."""
|
|
745
924
|
|
|
746
|
-
|
|
925
|
+
# Make a copy of only those rows in the slice range
|
|
747
926
|
rows = copy.deepcopy(self._rows[options["start"]:options["end"]])
|
|
748
927
|
# Sort if necessary
|
|
749
928
|
if options["sortby"]:
|
|
@@ -755,7 +934,13 @@ class PrettyTable(object):
|
|
|
755
934
|
# Undecorate
|
|
756
935
|
rows = [row[1:] for row in rows]
|
|
757
936
|
return rows
|
|
758
|
-
|
|
937
|
+
|
|
938
|
+
def _format_row(self, row, options):
|
|
939
|
+
return [self._format_value(field, value) for (field, value) in zip(self._field_names, row)]
|
|
940
|
+
|
|
941
|
+
def _format_rows(self, rows, options):
|
|
942
|
+
return [self._format_row(row, options) for row in rows]
|
|
943
|
+
|
|
759
944
|
##############################
|
|
760
945
|
# PLAIN TEXT STRING METHODS #
|
|
761
946
|
##############################
|
|
@@ -771,9 +956,10 @@ class PrettyTable(object):
|
|
|
771
956
|
fields - names of fields (columns) to include
|
|
772
957
|
header - print a header showing field names (True or False)
|
|
773
958
|
border - print a border around the table (True or False)
|
|
774
|
-
hrules - controls printing of horizontal rules after rows. Allowed values: FRAME,
|
|
775
|
-
|
|
776
|
-
|
|
959
|
+
hrules - controls printing of horizontal rules after rows. Allowed values: ALL, FRAME, HEADER, NONE
|
|
960
|
+
vrules - controls printing of vertical rules between columns. Allowed values: FRAME, ALL, NONE
|
|
961
|
+
int_format - controls formatting of integer data
|
|
962
|
+
float_format - controls formatting of floating point data
|
|
777
963
|
padding_width - number of spaces on either side of column data (only used if left and right paddings are None)
|
|
778
964
|
left_padding_width - number of spaces on left hand side of column data
|
|
779
965
|
right_padding_width - number of spaces on right hand side of column data
|
|
@@ -782,55 +968,67 @@ class PrettyTable(object):
|
|
|
782
968
|
junction_char - single character string used to draw line junctions
|
|
783
969
|
sortby - name of field to sort rows by
|
|
784
970
|
sort_key - sorting key function, applied to data points before sorting
|
|
785
|
-
reversesort - True or False to sort in descending or ascending order
|
|
971
|
+
reversesort - True or False to sort in descending or ascending order
|
|
972
|
+
print empty - if True, stringify just the header for an empty table, if False return an empty string """
|
|
786
973
|
|
|
787
974
|
options = self._get_options(kwargs)
|
|
788
975
|
|
|
789
|
-
|
|
976
|
+
lines = []
|
|
790
977
|
|
|
791
978
|
# Don't think too hard about an empty table
|
|
792
|
-
|
|
979
|
+
# Is this the desired behaviour? Maybe we should still print the header?
|
|
980
|
+
if self.rowcount == 0 and (not options["print_empty"] or not options["border"]):
|
|
793
981
|
return ""
|
|
794
982
|
|
|
983
|
+
# Get the rows we need to print, taking into account slicing, sorting, etc.
|
|
795
984
|
rows = self._get_rows(options)
|
|
796
|
-
self._compute_widths(rows, options)
|
|
797
985
|
|
|
798
|
-
#
|
|
799
|
-
|
|
800
|
-
# contains width-adjusting voodoo which has to be done first. This is ugly
|
|
801
|
-
# and Wrong and will change soon)
|
|
802
|
-
rowbits = []
|
|
803
|
-
for row in rows:
|
|
804
|
-
rowbits.append(self._stringify_row(row, options))
|
|
986
|
+
# Turn all data in all rows into Unicode, formatted as desired
|
|
987
|
+
formatted_rows = self._format_rows(rows, options)
|
|
805
988
|
|
|
989
|
+
# Compute column widths
|
|
990
|
+
self._compute_widths(formatted_rows, options)
|
|
806
991
|
|
|
807
992
|
# Add header or top of border
|
|
993
|
+
self._hrule = self._stringify_hrule(options)
|
|
808
994
|
if options["header"]:
|
|
809
|
-
|
|
810
|
-
elif options["border"] and options["hrules"]
|
|
811
|
-
|
|
995
|
+
lines.append(self._stringify_header(options))
|
|
996
|
+
elif options["border"] and options["hrules"] in (ALL, FRAME):
|
|
997
|
+
lines.append(self._hrule)
|
|
812
998
|
|
|
813
999
|
# Add rows
|
|
814
|
-
|
|
1000
|
+
for row in formatted_rows:
|
|
1001
|
+
lines.append(self._stringify_row(row, options))
|
|
815
1002
|
|
|
816
1003
|
# Add bottom of border
|
|
817
|
-
if options["border"] and
|
|
818
|
-
|
|
1004
|
+
if options["border"] and options["hrules"] == FRAME:
|
|
1005
|
+
lines.append(self._hrule)
|
|
819
1006
|
|
|
820
|
-
|
|
821
|
-
self._nonunicode = string
|
|
822
|
-
return _unicode(string)
|
|
1007
|
+
return self._unicode("\n").join(lines)
|
|
823
1008
|
|
|
824
1009
|
def _stringify_hrule(self, options):
|
|
825
1010
|
|
|
826
1011
|
if not options["border"]:
|
|
827
1012
|
return ""
|
|
828
1013
|
lpad, rpad = self._get_padding_widths(options)
|
|
829
|
-
|
|
1014
|
+
if options['vrules'] in (ALL, FRAME):
|
|
1015
|
+
bits = [options["junction_char"]]
|
|
1016
|
+
else:
|
|
1017
|
+
bits = [options["horizontal_char"]]
|
|
1018
|
+
# For tables with no data or fieldnames
|
|
1019
|
+
if not self._field_names:
|
|
1020
|
+
bits.append(options["junction_char"])
|
|
1021
|
+
return "".join(bits)
|
|
830
1022
|
for field, width in zip(self._field_names, self._widths):
|
|
831
1023
|
if options["fields"] and field not in options["fields"]:
|
|
832
1024
|
continue
|
|
833
1025
|
bits.append((width+lpad+rpad)*options["horizontal_char"])
|
|
1026
|
+
if options['vrules'] == ALL:
|
|
1027
|
+
bits.append(options["junction_char"])
|
|
1028
|
+
else:
|
|
1029
|
+
bits.append(options["horizontal_char"])
|
|
1030
|
+
if options["vrules"] == FRAME:
|
|
1031
|
+
bits.pop()
|
|
834
1032
|
bits.append(options["junction_char"])
|
|
835
1033
|
return "".join(bits)
|
|
836
1034
|
|
|
@@ -839,54 +1037,62 @@ class PrettyTable(object):
|
|
|
839
1037
|
bits = []
|
|
840
1038
|
lpad, rpad = self._get_padding_widths(options)
|
|
841
1039
|
if options["border"]:
|
|
842
|
-
if options["hrules"]
|
|
1040
|
+
if options["hrules"] in (ALL, FRAME):
|
|
843
1041
|
bits.append(self._hrule)
|
|
844
1042
|
bits.append("\n")
|
|
845
|
-
|
|
1043
|
+
if options["vrules"] in (ALL, FRAME):
|
|
1044
|
+
bits.append(options["vertical_char"])
|
|
1045
|
+
else:
|
|
1046
|
+
bits.append(" ")
|
|
1047
|
+
# For tables with no data or field names
|
|
1048
|
+
if not self._field_names:
|
|
1049
|
+
if options["vrules"] in (ALL, FRAME):
|
|
1050
|
+
bits.append(options["vertical_char"])
|
|
1051
|
+
else:
|
|
1052
|
+
bits.append(" ")
|
|
846
1053
|
for field, width, in zip(self._field_names, self._widths):
|
|
847
1054
|
if options["fields"] and field not in options["fields"]:
|
|
848
1055
|
continue
|
|
849
|
-
if self.
|
|
850
|
-
|
|
851
|
-
elif self.
|
|
852
|
-
|
|
1056
|
+
if self._header_style == "cap":
|
|
1057
|
+
fieldname = field.capitalize()
|
|
1058
|
+
elif self._header_style == "title":
|
|
1059
|
+
fieldname = field.title()
|
|
1060
|
+
elif self._header_style == "upper":
|
|
1061
|
+
fieldname = field.upper()
|
|
1062
|
+
elif self._header_style == "lower":
|
|
1063
|
+
fieldname = field.lower()
|
|
853
1064
|
else:
|
|
854
|
-
|
|
1065
|
+
fieldname = field
|
|
1066
|
+
bits.append(" " * lpad + self._justify(fieldname, width, self._align[field]) + " " * rpad)
|
|
855
1067
|
if options["border"]:
|
|
856
|
-
|
|
1068
|
+
if options["vrules"] == ALL:
|
|
1069
|
+
bits.append(options["vertical_char"])
|
|
1070
|
+
else:
|
|
1071
|
+
bits.append(" ")
|
|
1072
|
+
# If vrules is FRAME, then we just appended a space at the end
|
|
1073
|
+
# of the last field, when we really want a vertical character
|
|
1074
|
+
if options["border"] and options["vrules"] == FRAME:
|
|
1075
|
+
bits.pop()
|
|
1076
|
+
bits.append(options["vertical_char"])
|
|
857
1077
|
if options["border"] and options["hrules"] != NONE:
|
|
858
1078
|
bits.append("\n")
|
|
859
1079
|
bits.append(self._hrule)
|
|
860
1080
|
return "".join(bits)
|
|
861
1081
|
|
|
862
1082
|
def _stringify_row(self, row, options):
|
|
863
|
-
|
|
864
|
-
for index, value in enumerate(row):
|
|
865
|
-
row[index] = self._format_value(self.field_names[index], value)
|
|
866
|
-
|
|
1083
|
+
|
|
867
1084
|
for index, field, value, width, in zip(range(0,len(row)), self._field_names, row, self._widths):
|
|
868
1085
|
# Enforce max widths
|
|
869
|
-
|
|
870
|
-
lines = _unicode(value).split("\n")
|
|
1086
|
+
lines = value.split("\n")
|
|
871
1087
|
new_lines = []
|
|
872
1088
|
for line in lines:
|
|
873
|
-
if
|
|
874
|
-
line = textwrap.fill(line,
|
|
1089
|
+
if _str_block_width(line) > width:
|
|
1090
|
+
line = textwrap.fill(line, width)
|
|
875
1091
|
new_lines.append(line)
|
|
876
1092
|
lines = new_lines
|
|
877
1093
|
value = "\n".join(lines)
|
|
878
1094
|
row[index] = value
|
|
879
1095
|
|
|
880
|
-
#old_widths = self._widths[:]
|
|
881
|
-
|
|
882
|
-
for index, field in enumerate(self._field_names):
|
|
883
|
-
namewidth = len(field)
|
|
884
|
-
datawidth = min(self._widths[index], self._max_width.get(field, self._widths[index]))
|
|
885
|
-
if options["header"]:
|
|
886
|
-
self._widths[index] = max(namewidth, datawidth)
|
|
887
|
-
else:
|
|
888
|
-
self._widths[index] = datawidth
|
|
889
|
-
|
|
890
1096
|
row_height = 0
|
|
891
1097
|
for c in row:
|
|
892
1098
|
h = _get_size(c)[1]
|
|
@@ -898,31 +1104,43 @@ class PrettyTable(object):
|
|
|
898
1104
|
for y in range(0, row_height):
|
|
899
1105
|
bits.append([])
|
|
900
1106
|
if options["border"]:
|
|
901
|
-
|
|
1107
|
+
if options["vrules"] in (ALL, FRAME):
|
|
1108
|
+
bits[y].append(self.vertical_char)
|
|
1109
|
+
else:
|
|
1110
|
+
bits[y].append(" ")
|
|
902
1111
|
|
|
903
1112
|
for field, value, width, in zip(self._field_names, row, self._widths):
|
|
904
1113
|
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
1114
|
+
valign = self._valign[field]
|
|
1115
|
+
lines = value.split("\n")
|
|
1116
|
+
dHeight = row_height - len(lines)
|
|
1117
|
+
if dHeight:
|
|
1118
|
+
if valign == "m":
|
|
1119
|
+
lines = [""] * int(dHeight / 2) + lines + [""] * (dHeight - int(dHeight / 2))
|
|
1120
|
+
elif valign == "b":
|
|
1121
|
+
lines = [""] * dHeight + lines
|
|
1122
|
+
else:
|
|
1123
|
+
lines = lines + [""] * dHeight
|
|
908
1124
|
|
|
909
1125
|
y = 0
|
|
910
1126
|
for l in lines:
|
|
911
1127
|
if options["fields"] and field not in options["fields"]:
|
|
912
1128
|
continue
|
|
913
1129
|
|
|
914
|
-
|
|
915
|
-
bits[y].append(" " * lpad + _unicode(l).ljust(width) + " " * rpad)
|
|
916
|
-
elif self._align[field] == "r":
|
|
917
|
-
bits[y].append(" " * lpad + _unicode(l).rjust(width) + " " * rpad)
|
|
918
|
-
else:
|
|
919
|
-
bits[y].append(" " * lpad + _unicode(l).center(width) + " " * rpad)
|
|
1130
|
+
bits[y].append(" " * lpad + self._justify(l, width, self._align[field]) + " " * rpad)
|
|
920
1131
|
if options["border"]:
|
|
921
|
-
|
|
922
|
-
|
|
1132
|
+
if options["vrules"] == ALL:
|
|
1133
|
+
bits[y].append(self.vertical_char)
|
|
1134
|
+
else:
|
|
1135
|
+
bits[y].append(" ")
|
|
923
1136
|
y += 1
|
|
924
1137
|
|
|
925
|
-
|
|
1138
|
+
# If vrules is FRAME, then we just appended a space at the end
|
|
1139
|
+
# of the last field, when we really want a vertical character
|
|
1140
|
+
for y in range(0, row_height):
|
|
1141
|
+
if options["border"] and options["vrules"] == FRAME:
|
|
1142
|
+
bits[y].pop()
|
|
1143
|
+
bits[y].append(options["vertical_char"])
|
|
926
1144
|
|
|
927
1145
|
if options["border"] and options["hrules"]== ALL:
|
|
928
1146
|
bits[row_height-1].append("\n")
|
|
@@ -931,8 +1149,6 @@ class PrettyTable(object):
|
|
|
931
1149
|
for y in range(0, row_height):
|
|
932
1150
|
bits[y] = "".join(bits[y])
|
|
933
1151
|
|
|
934
|
-
#self._widths = old_widths
|
|
935
|
-
|
|
936
1152
|
return "\n".join(bits)
|
|
937
1153
|
|
|
938
1154
|
##############################
|
|
@@ -950,15 +1166,17 @@ class PrettyTable(object):
|
|
|
950
1166
|
fields - names of fields (columns) to include
|
|
951
1167
|
header - print a header showing field names (True or False)
|
|
952
1168
|
border - print a border around the table (True or False)
|
|
953
|
-
hrules - controls printing of horizontal rules after rows. Allowed values: FRAME,
|
|
954
|
-
|
|
955
|
-
|
|
1169
|
+
hrules - controls printing of horizontal rules after rows. Allowed values: ALL, FRAME, HEADER, NONE
|
|
1170
|
+
vrules - controls printing of vertical rules between columns. Allowed values: FRAME, ALL, NONE
|
|
1171
|
+
int_format - controls formatting of integer data
|
|
1172
|
+
float_format - controls formatting of floating point data
|
|
956
1173
|
padding_width - number of spaces on either side of column data (only used if left and right paddings are None)
|
|
957
1174
|
left_padding_width - number of spaces on left hand side of column data
|
|
958
1175
|
right_padding_width - number of spaces on right hand side of column data
|
|
959
1176
|
sortby - name of field to sort rows by
|
|
960
1177
|
sort_key - sorting key function, applied to data points before sorting
|
|
961
|
-
attributes - dictionary of name/value pairs to include as HTML attributes in the <table> tag
|
|
1178
|
+
attributes - dictionary of name/value pairs to include as HTML attributes in the <table> tag
|
|
1179
|
+
xhtml - print <br/> tags if True, <br> tags if false"""
|
|
962
1180
|
|
|
963
1181
|
options = self._get_options(kwargs)
|
|
964
1182
|
|
|
@@ -967,97 +1185,282 @@ class PrettyTable(object):
|
|
|
967
1185
|
else:
|
|
968
1186
|
string = self._get_simple_html_string(options)
|
|
969
1187
|
|
|
970
|
-
|
|
971
|
-
return _unicode(string)
|
|
1188
|
+
return string
|
|
972
1189
|
|
|
973
1190
|
def _get_simple_html_string(self, options):
|
|
974
1191
|
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
1192
|
+
lines = []
|
|
1193
|
+
if options["xhtml"]:
|
|
1194
|
+
linebreak = "<br/>"
|
|
1195
|
+
else:
|
|
1196
|
+
linebreak = "<br>"
|
|
1197
|
+
|
|
1198
|
+
open_tag = []
|
|
1199
|
+
open_tag.append("<table")
|
|
980
1200
|
if options["attributes"]:
|
|
981
1201
|
for attr_name in options["attributes"]:
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
1202
|
+
open_tag.append(" %s=\"%s\"" % (attr_name, options["attributes"][attr_name]))
|
|
1203
|
+
open_tag.append(">")
|
|
1204
|
+
lines.append("".join(open_tag))
|
|
985
1205
|
|
|
986
1206
|
# Headers
|
|
987
1207
|
if options["header"]:
|
|
988
|
-
|
|
1208
|
+
lines.append(" <tr>")
|
|
989
1209
|
for field in self._field_names:
|
|
990
1210
|
if options["fields"] and field not in options["fields"]:
|
|
991
1211
|
continue
|
|
992
|
-
|
|
993
|
-
|
|
1212
|
+
lines.append(" <th>%s</th>" % escape(field).replace("\n", linebreak))
|
|
1213
|
+
lines.append(" </tr>")
|
|
994
1214
|
|
|
995
1215
|
# Data
|
|
996
1216
|
rows = self._get_rows(options)
|
|
997
|
-
|
|
998
|
-
|
|
1217
|
+
formatted_rows = self._format_rows(rows, options)
|
|
1218
|
+
for row in formatted_rows:
|
|
1219
|
+
lines.append(" <tr>")
|
|
999
1220
|
for field, datum in zip(self._field_names, row):
|
|
1000
1221
|
if options["fields"] and field not in options["fields"]:
|
|
1001
1222
|
continue
|
|
1002
|
-
|
|
1003
|
-
|
|
1223
|
+
lines.append(" <td>%s</td>" % escape(datum).replace("\n", linebreak))
|
|
1224
|
+
lines.append(" </tr>")
|
|
1004
1225
|
|
|
1005
|
-
|
|
1006
|
-
string = "\n".join(bits)
|
|
1226
|
+
lines.append("</table>")
|
|
1007
1227
|
|
|
1008
|
-
self.
|
|
1009
|
-
return _unicode(string)
|
|
1228
|
+
return self._unicode("\n").join(lines)
|
|
1010
1229
|
|
|
1011
1230
|
def _get_formatted_html_string(self, options):
|
|
1012
1231
|
|
|
1013
|
-
|
|
1232
|
+
lines = []
|
|
1014
1233
|
lpad, rpad = self._get_padding_widths(options)
|
|
1015
|
-
|
|
1016
|
-
|
|
1234
|
+
if options["xhtml"]:
|
|
1235
|
+
linebreak = "<br/>"
|
|
1236
|
+
else:
|
|
1237
|
+
linebreak = "<br>"
|
|
1238
|
+
|
|
1239
|
+
open_tag = []
|
|
1240
|
+
open_tag.append("<table")
|
|
1017
1241
|
if options["border"]:
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1242
|
+
if options["hrules"] == ALL and options["vrules"] == ALL:
|
|
1243
|
+
open_tag.append(" frame=\"box\" rules=\"all\"")
|
|
1244
|
+
elif options["hrules"] == FRAME and options["vrules"] == FRAME:
|
|
1245
|
+
open_tag.append(" frame=\"box\"")
|
|
1246
|
+
elif options["hrules"] == FRAME and options["vrules"] == ALL:
|
|
1247
|
+
open_tag.append(" frame=\"box\" rules=\"cols\"")
|
|
1248
|
+
elif options["hrules"] == FRAME:
|
|
1249
|
+
open_tag.append(" frame=\"hsides\"")
|
|
1250
|
+
elif options["hrules"] == ALL:
|
|
1251
|
+
open_tag.append(" frame=\"hsides\" rules=\"rows\"")
|
|
1252
|
+
elif options["vrules"] == FRAME:
|
|
1253
|
+
open_tag.append(" frame=\"vsides\"")
|
|
1254
|
+
elif options["vrules"] == ALL:
|
|
1255
|
+
open_tag.append(" frame=\"vsides\" rules=\"cols\"")
|
|
1021
1256
|
if options["attributes"]:
|
|
1022
1257
|
for attr_name in options["attributes"]:
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1258
|
+
open_tag.append(" %s=\"%s\"" % (attr_name, options["attributes"][attr_name]))
|
|
1259
|
+
open_tag.append(">")
|
|
1260
|
+
lines.append("".join(open_tag))
|
|
1261
|
+
|
|
1026
1262
|
# Headers
|
|
1027
1263
|
if options["header"]:
|
|
1028
|
-
|
|
1264
|
+
lines.append(" <tr>")
|
|
1029
1265
|
for field in self._field_names:
|
|
1030
1266
|
if options["fields"] and field not in options["fields"]:
|
|
1031
1267
|
continue
|
|
1032
|
-
|
|
1033
|
-
|
|
1268
|
+
lines.append(" <th style=\"padding-left: %dem; padding-right: %dem; text-align: center\">%s</th>" % (lpad, rpad, escape(field).replace("\n", linebreak)))
|
|
1269
|
+
lines.append(" </tr>")
|
|
1270
|
+
|
|
1034
1271
|
# Data
|
|
1035
1272
|
rows = self._get_rows(options)
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1273
|
+
formatted_rows = self._format_rows(rows, options)
|
|
1274
|
+
aligns = []
|
|
1275
|
+
valigns = []
|
|
1276
|
+
for field in self._field_names:
|
|
1277
|
+
aligns.append({ "l" : "left", "r" : "right", "c" : "center" }[self._align[field]])
|
|
1278
|
+
valigns.append({"t" : "top", "m" : "middle", "b" : "bottom"}[self._valign[field]])
|
|
1279
|
+
for row in formatted_rows:
|
|
1280
|
+
lines.append(" <tr>")
|
|
1281
|
+
for field, datum, align, valign in zip(self._field_names, row, aligns, valigns):
|
|
1039
1282
|
if options["fields"] and field not in options["fields"]:
|
|
1040
1283
|
continue
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1284
|
+
lines.append(" <td style=\"padding-left: %dem; padding-right: %dem; text-align: %s; vertical-align: %s\">%s</td>" % (lpad, rpad, align, valign, escape(datum).replace("\n", linebreak)))
|
|
1285
|
+
lines.append(" </tr>")
|
|
1286
|
+
lines.append("</table>")
|
|
1287
|
+
|
|
1288
|
+
return self._unicode("\n").join(lines)
|
|
1289
|
+
|
|
1290
|
+
##############################
|
|
1291
|
+
# UNICODE WIDTH FUNCTIONS #
|
|
1292
|
+
##############################
|
|
1293
|
+
|
|
1294
|
+
def _char_block_width(char):
|
|
1295
|
+
# Basic Latin, which is probably the most common case
|
|
1296
|
+
#if char in xrange(0x0021, 0x007e):
|
|
1297
|
+
#if char >= 0x0021 and char <= 0x007e:
|
|
1298
|
+
if 0x0021 <= char <= 0x007e:
|
|
1299
|
+
return 1
|
|
1300
|
+
# Chinese, Japanese, Korean (common)
|
|
1301
|
+
if 0x4e00 <= char <= 0x9fff:
|
|
1302
|
+
return 2
|
|
1303
|
+
# Hangul
|
|
1304
|
+
if 0xac00 <= char <= 0xd7af:
|
|
1305
|
+
return 2
|
|
1306
|
+
# Combining?
|
|
1307
|
+
if unicodedata.combining(uni_chr(char)):
|
|
1308
|
+
return 0
|
|
1309
|
+
# Hiragana and Katakana
|
|
1310
|
+
if 0x3040 <= char <= 0x309f or 0x30a0 <= char <= 0x30ff:
|
|
1311
|
+
return 2
|
|
1312
|
+
# Full-width Latin characters
|
|
1313
|
+
if 0xff01 <= char <= 0xff60:
|
|
1314
|
+
return 2
|
|
1315
|
+
# CJK punctuation
|
|
1316
|
+
if 0x3000 <= char <= 0x303e:
|
|
1317
|
+
return 2
|
|
1318
|
+
# Backspace and delete
|
|
1319
|
+
if char in (0x0008, 0x007f):
|
|
1320
|
+
return -1
|
|
1321
|
+
# Other control characters
|
|
1322
|
+
elif char in (0x0000, 0x001f):
|
|
1323
|
+
return 0
|
|
1324
|
+
# Take a guess
|
|
1325
|
+
return 1
|
|
1326
|
+
|
|
1327
|
+
def _str_block_width(val):
|
|
1328
|
+
|
|
1329
|
+
return sum(itermap(_char_block_width, itermap(ord, _re.sub("", val))))
|
|
1330
|
+
|
|
1331
|
+
##############################
|
|
1332
|
+
# TABLE FACTORIES #
|
|
1333
|
+
##############################
|
|
1334
|
+
|
|
1335
|
+
def from_csv(fp, field_names = None, **kwargs):
|
|
1336
|
+
|
|
1337
|
+
dialect = csv.Sniffer().sniff(fp.read(1024))
|
|
1338
|
+
fp.seek(0)
|
|
1339
|
+
reader = csv.reader(fp, dialect)
|
|
1340
|
+
|
|
1341
|
+
table = PrettyTable(**kwargs)
|
|
1342
|
+
if field_names:
|
|
1343
|
+
table.field_names = field_names
|
|
1344
|
+
else:
|
|
1345
|
+
if py3k:
|
|
1346
|
+
table.field_names = [x.strip() for x in next(reader)]
|
|
1347
|
+
else:
|
|
1348
|
+
table.field_names = [x.strip() for x in reader.next()]
|
|
1349
|
+
|
|
1350
|
+
for row in reader:
|
|
1351
|
+
table.add_row([x.strip() for x in row])
|
|
1352
|
+
|
|
1353
|
+
return table
|
|
1354
|
+
|
|
1355
|
+
def from_db_cursor(cursor, **kwargs):
|
|
1356
|
+
|
|
1357
|
+
if cursor.description:
|
|
1358
|
+
table = PrettyTable(**kwargs)
|
|
1359
|
+
table.field_names = [col[0] for col in cursor.description]
|
|
1360
|
+
for row in cursor.fetchall():
|
|
1361
|
+
table.add_row(row)
|
|
1362
|
+
return table
|
|
1363
|
+
|
|
1364
|
+
class TableHandler(HTMLParser):
|
|
1365
|
+
|
|
1366
|
+
def __init__(self, **kwargs):
|
|
1367
|
+
HTMLParser.__init__(self)
|
|
1368
|
+
self.kwargs = kwargs
|
|
1369
|
+
self.tables = []
|
|
1370
|
+
self.last_row = []
|
|
1371
|
+
self.rows = []
|
|
1372
|
+
self.max_row_width = 0
|
|
1373
|
+
self.active = None
|
|
1374
|
+
self.last_content = ""
|
|
1375
|
+
self.is_last_row_header = False
|
|
1376
|
+
|
|
1377
|
+
def handle_starttag(self,tag, attrs):
|
|
1378
|
+
self.active = tag
|
|
1379
|
+
if tag == "th":
|
|
1380
|
+
self.is_last_row_header = True
|
|
1381
|
+
|
|
1382
|
+
def handle_endtag(self,tag):
|
|
1383
|
+
if tag in ["th", "td"]:
|
|
1384
|
+
stripped_content = self.last_content.strip()
|
|
1385
|
+
self.last_row.append(stripped_content)
|
|
1386
|
+
if tag == "tr":
|
|
1387
|
+
self.rows.append(
|
|
1388
|
+
(self.last_row, self.is_last_row_header))
|
|
1389
|
+
self.max_row_width = max(self.max_row_width, len(self.last_row))
|
|
1390
|
+
self.last_row = []
|
|
1391
|
+
self.is_last_row_header = False
|
|
1392
|
+
if tag == "table":
|
|
1393
|
+
table = self.generate_table(self.rows)
|
|
1394
|
+
self.tables.append(table)
|
|
1395
|
+
self.rows = []
|
|
1396
|
+
self.last_content = " "
|
|
1397
|
+
self.active = None
|
|
1398
|
+
|
|
1399
|
+
|
|
1400
|
+
def handle_data(self, data):
|
|
1401
|
+
self.last_content += data
|
|
1402
|
+
|
|
1403
|
+
def generate_table(self, rows):
|
|
1404
|
+
"""
|
|
1405
|
+
Generates from a list of rows a PrettyTable object.
|
|
1406
|
+
"""
|
|
1407
|
+
table = PrettyTable(**self.kwargs)
|
|
1408
|
+
for row in self.rows:
|
|
1409
|
+
if len(row[0]) < self.max_row_width:
|
|
1410
|
+
appends = self.max_row_width - len(row[0])
|
|
1411
|
+
for i in range(1,appends):
|
|
1412
|
+
row[0].append("-")
|
|
1413
|
+
|
|
1414
|
+
if row[1] == True:
|
|
1415
|
+
self.make_fields_unique(row[0])
|
|
1416
|
+
table.field_names = row[0]
|
|
1417
|
+
else:
|
|
1418
|
+
table.add_row(row[0])
|
|
1419
|
+
return table
|
|
1420
|
+
|
|
1421
|
+
def make_fields_unique(self, fields):
|
|
1422
|
+
"""
|
|
1423
|
+
iterates over the row and make each field unique
|
|
1424
|
+
"""
|
|
1425
|
+
for i in range(0, len(fields)):
|
|
1426
|
+
for j in range(i+1, len(fields)):
|
|
1427
|
+
if fields[i] == fields[j]:
|
|
1428
|
+
fields[j] += "'"
|
|
1429
|
+
|
|
1430
|
+
def from_html(html_code, **kwargs):
|
|
1431
|
+
"""
|
|
1432
|
+
Generates a list of PrettyTables from a string of HTML code. Each <table> in
|
|
1433
|
+
the HTML becomes one PrettyTable object.
|
|
1434
|
+
"""
|
|
1435
|
+
|
|
1436
|
+
parser = TableHandler(**kwargs)
|
|
1437
|
+
parser.feed(html_code)
|
|
1438
|
+
return parser.tables
|
|
1439
|
+
|
|
1440
|
+
def from_html_one(html_code, **kwargs):
|
|
1441
|
+
"""
|
|
1442
|
+
Generates a PrettyTables from a string of HTML code which contains only a
|
|
1443
|
+
single <table>
|
|
1444
|
+
"""
|
|
1445
|
+
|
|
1446
|
+
tables = from_html(html_code, **kwargs)
|
|
1447
|
+
try:
|
|
1448
|
+
assert len(tables) == 1
|
|
1449
|
+
except AssertionError:
|
|
1450
|
+
raise Exception("More than one <table> in provided HTML code! Use from_html instead.")
|
|
1451
|
+
return tables[0]
|
|
1452
|
+
|
|
1453
|
+
##############################
|
|
1454
|
+
# MAIN (TEST FUNCTION) #
|
|
1455
|
+
##############################
|
|
1053
1456
|
|
|
1054
1457
|
def main():
|
|
1055
1458
|
|
|
1056
1459
|
x = PrettyTable(["City name", "Area", "Population", "Annual Rainfall"])
|
|
1057
1460
|
x.sortby = "Population"
|
|
1058
1461
|
x.reversesort = True
|
|
1059
|
-
x.int_format["Area"] = "
|
|
1060
|
-
x.float_format = "6.
|
|
1462
|
+
x.int_format["Area"] = "04d"
|
|
1463
|
+
x.float_format = "6.1f"
|
|
1061
1464
|
x.align["City name"] = "l" # Left align city names
|
|
1062
1465
|
x.add_row(["Adelaide", 1295, 1158259, 600.5])
|
|
1063
1466
|
x.add_row(["Brisbane", 5905, 1857594, 1146.4])
|