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