1 | n/a | """More comprehensive traceback formatting for Python scripts. |
---|
2 | n/a | |
---|
3 | n/a | To enable this module, do: |
---|
4 | n/a | |
---|
5 | n/a | import cgitb; cgitb.enable() |
---|
6 | n/a | |
---|
7 | n/a | at the top of your script. The optional arguments to enable() are: |
---|
8 | n/a | |
---|
9 | n/a | display - if true, tracebacks are displayed in the web browser |
---|
10 | n/a | logdir - if set, tracebacks are written to files in this directory |
---|
11 | n/a | context - number of lines of source code to show for each stack frame |
---|
12 | n/a | format - 'text' or 'html' controls the output format |
---|
13 | n/a | |
---|
14 | n/a | By default, tracebacks are displayed but not saved, the context is 5 lines |
---|
15 | n/a | and the output format is 'html' (for backwards compatibility with the |
---|
16 | n/a | original use of this module) |
---|
17 | n/a | |
---|
18 | n/a | Alternatively, if you have caught an exception and want cgitb to display it |
---|
19 | n/a | for you, call cgitb.handler(). The optional argument to handler() is a |
---|
20 | n/a | 3-item tuple (etype, evalue, etb) just like the value of sys.exc_info(). |
---|
21 | n/a | The default handler displays output as HTML. |
---|
22 | n/a | |
---|
23 | n/a | """ |
---|
24 | n/a | import inspect |
---|
25 | n/a | import keyword |
---|
26 | n/a | import linecache |
---|
27 | n/a | import os |
---|
28 | n/a | import pydoc |
---|
29 | n/a | import sys |
---|
30 | n/a | import tempfile |
---|
31 | n/a | import time |
---|
32 | n/a | import tokenize |
---|
33 | n/a | import traceback |
---|
34 | n/a | |
---|
35 | n/a | def reset(): |
---|
36 | n/a | """Return a string that resets the CGI and browser to a known state.""" |
---|
37 | n/a | return '''<!--: spam |
---|
38 | n/a | Content-Type: text/html |
---|
39 | n/a | |
---|
40 | n/a | <body bgcolor="#f0f0f8"><font color="#f0f0f8" size="-5"> --> |
---|
41 | n/a | <body bgcolor="#f0f0f8"><font color="#f0f0f8" size="-5"> --> --> |
---|
42 | n/a | </font> </font> </font> </script> </object> </blockquote> </pre> |
---|
43 | n/a | </table> </table> </table> </table> </table> </font> </font> </font>''' |
---|
44 | n/a | |
---|
45 | n/a | __UNDEF__ = [] # a special sentinel object |
---|
46 | n/a | def small(text): |
---|
47 | n/a | if text: |
---|
48 | n/a | return '<small>' + text + '</small>' |
---|
49 | n/a | else: |
---|
50 | n/a | return '' |
---|
51 | n/a | |
---|
52 | n/a | def strong(text): |
---|
53 | n/a | if text: |
---|
54 | n/a | return '<strong>' + text + '</strong>' |
---|
55 | n/a | else: |
---|
56 | n/a | return '' |
---|
57 | n/a | |
---|
58 | n/a | def grey(text): |
---|
59 | n/a | if text: |
---|
60 | n/a | return '<font color="#909090">' + text + '</font>' |
---|
61 | n/a | else: |
---|
62 | n/a | return '' |
---|
63 | n/a | |
---|
64 | n/a | def lookup(name, frame, locals): |
---|
65 | n/a | """Find the value for a given name in the given environment.""" |
---|
66 | n/a | if name in locals: |
---|
67 | n/a | return 'local', locals[name] |
---|
68 | n/a | if name in frame.f_globals: |
---|
69 | n/a | return 'global', frame.f_globals[name] |
---|
70 | n/a | if '__builtins__' in frame.f_globals: |
---|
71 | n/a | builtins = frame.f_globals['__builtins__'] |
---|
72 | n/a | if type(builtins) is type({}): |
---|
73 | n/a | if name in builtins: |
---|
74 | n/a | return 'builtin', builtins[name] |
---|
75 | n/a | else: |
---|
76 | n/a | if hasattr(builtins, name): |
---|
77 | n/a | return 'builtin', getattr(builtins, name) |
---|
78 | n/a | return None, __UNDEF__ |
---|
79 | n/a | |
---|
80 | n/a | def scanvars(reader, frame, locals): |
---|
81 | n/a | """Scan one logical line of Python and look up values of variables used.""" |
---|
82 | n/a | vars, lasttoken, parent, prefix, value = [], None, None, '', __UNDEF__ |
---|
83 | n/a | for ttype, token, start, end, line in tokenize.generate_tokens(reader): |
---|
84 | n/a | if ttype == tokenize.NEWLINE: break |
---|
85 | n/a | if ttype == tokenize.NAME and token not in keyword.kwlist: |
---|
86 | n/a | if lasttoken == '.': |
---|
87 | n/a | if parent is not __UNDEF__: |
---|
88 | n/a | value = getattr(parent, token, __UNDEF__) |
---|
89 | n/a | vars.append((prefix + token, prefix, value)) |
---|
90 | n/a | else: |
---|
91 | n/a | where, value = lookup(token, frame, locals) |
---|
92 | n/a | vars.append((token, where, value)) |
---|
93 | n/a | elif token == '.': |
---|
94 | n/a | prefix += lasttoken + '.' |
---|
95 | n/a | parent = value |
---|
96 | n/a | else: |
---|
97 | n/a | parent, prefix = None, '' |
---|
98 | n/a | lasttoken = token |
---|
99 | n/a | return vars |
---|
100 | n/a | |
---|
101 | n/a | def html(einfo, context=5): |
---|
102 | n/a | """Return a nice HTML document describing a given traceback.""" |
---|
103 | n/a | etype, evalue, etb = einfo |
---|
104 | n/a | if isinstance(etype, type): |
---|
105 | n/a | etype = etype.__name__ |
---|
106 | n/a | pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable |
---|
107 | n/a | date = time.ctime(time.time()) |
---|
108 | n/a | head = '<body bgcolor="#f0f0f8">' + pydoc.html.heading( |
---|
109 | n/a | '<big><big>%s</big></big>' % |
---|
110 | n/a | strong(pydoc.html.escape(str(etype))), |
---|
111 | n/a | '#ffffff', '#6622aa', pyver + '<br>' + date) + ''' |
---|
112 | n/a | <p>A problem occurred in a Python script. Here is the sequence of |
---|
113 | n/a | function calls leading up to the error, in the order they occurred.</p>''' |
---|
114 | n/a | |
---|
115 | n/a | indent = '<tt>' + small(' ' * 5) + ' </tt>' |
---|
116 | n/a | frames = [] |
---|
117 | n/a | records = inspect.getinnerframes(etb, context) |
---|
118 | n/a | for frame, file, lnum, func, lines, index in records: |
---|
119 | n/a | if file: |
---|
120 | n/a | file = os.path.abspath(file) |
---|
121 | n/a | link = '<a href="file://%s">%s</a>' % (file, pydoc.html.escape(file)) |
---|
122 | n/a | else: |
---|
123 | n/a | file = link = '?' |
---|
124 | n/a | args, varargs, varkw, locals = inspect.getargvalues(frame) |
---|
125 | n/a | call = '' |
---|
126 | n/a | if func != '?': |
---|
127 | n/a | call = 'in ' + strong(func) + \ |
---|
128 | n/a | inspect.formatargvalues(args, varargs, varkw, locals, |
---|
129 | n/a | formatvalue=lambda value: '=' + pydoc.html.repr(value)) |
---|
130 | n/a | |
---|
131 | n/a | highlight = {} |
---|
132 | n/a | def reader(lnum=[lnum]): |
---|
133 | n/a | highlight[lnum[0]] = 1 |
---|
134 | n/a | try: return linecache.getline(file, lnum[0]) |
---|
135 | n/a | finally: lnum[0] += 1 |
---|
136 | n/a | vars = scanvars(reader, frame, locals) |
---|
137 | n/a | |
---|
138 | n/a | rows = ['<tr><td bgcolor="#d8bbff">%s%s %s</td></tr>' % |
---|
139 | n/a | ('<big> </big>', link, call)] |
---|
140 | n/a | if index is not None: |
---|
141 | n/a | i = lnum - index |
---|
142 | n/a | for line in lines: |
---|
143 | n/a | num = small(' ' * (5-len(str(i))) + str(i)) + ' ' |
---|
144 | n/a | if i in highlight: |
---|
145 | n/a | line = '<tt>=>%s%s</tt>' % (num, pydoc.html.preformat(line)) |
---|
146 | n/a | rows.append('<tr><td bgcolor="#ffccee">%s</td></tr>' % line) |
---|
147 | n/a | else: |
---|
148 | n/a | line = '<tt> %s%s</tt>' % (num, pydoc.html.preformat(line)) |
---|
149 | n/a | rows.append('<tr><td>%s</td></tr>' % grey(line)) |
---|
150 | n/a | i += 1 |
---|
151 | n/a | |
---|
152 | n/a | done, dump = {}, [] |
---|
153 | n/a | for name, where, value in vars: |
---|
154 | n/a | if name in done: continue |
---|
155 | n/a | done[name] = 1 |
---|
156 | n/a | if value is not __UNDEF__: |
---|
157 | n/a | if where in ('global', 'builtin'): |
---|
158 | n/a | name = ('<em>%s</em> ' % where) + strong(name) |
---|
159 | n/a | elif where == 'local': |
---|
160 | n/a | name = strong(name) |
---|
161 | n/a | else: |
---|
162 | n/a | name = where + strong(name.split('.')[-1]) |
---|
163 | n/a | dump.append('%s = %s' % (name, pydoc.html.repr(value))) |
---|
164 | n/a | else: |
---|
165 | n/a | dump.append(name + ' <em>undefined</em>') |
---|
166 | n/a | |
---|
167 | n/a | rows.append('<tr><td>%s</td></tr>' % small(grey(', '.join(dump)))) |
---|
168 | n/a | frames.append(''' |
---|
169 | n/a | <table width="100%%" cellspacing=0 cellpadding=0 border=0> |
---|
170 | n/a | %s</table>''' % '\n'.join(rows)) |
---|
171 | n/a | |
---|
172 | n/a | exception = ['<p>%s: %s' % (strong(pydoc.html.escape(str(etype))), |
---|
173 | n/a | pydoc.html.escape(str(evalue)))] |
---|
174 | n/a | for name in dir(evalue): |
---|
175 | n/a | if name[:1] == '_': continue |
---|
176 | n/a | value = pydoc.html.repr(getattr(evalue, name)) |
---|
177 | n/a | exception.append('\n<br>%s%s =\n%s' % (indent, name, value)) |
---|
178 | n/a | |
---|
179 | n/a | return head + ''.join(frames) + ''.join(exception) + ''' |
---|
180 | n/a | |
---|
181 | n/a | |
---|
182 | n/a | <!-- The above is a description of an error in a Python program, formatted |
---|
183 | n/a | for a Web browser because the 'cgitb' module was enabled. In case you |
---|
184 | n/a | are not reading this in a Web browser, here is the original traceback: |
---|
185 | n/a | |
---|
186 | n/a | %s |
---|
187 | n/a | --> |
---|
188 | n/a | ''' % pydoc.html.escape( |
---|
189 | n/a | ''.join(traceback.format_exception(etype, evalue, etb))) |
---|
190 | n/a | |
---|
191 | n/a | def text(einfo, context=5): |
---|
192 | n/a | """Return a plain text document describing a given traceback.""" |
---|
193 | n/a | etype, evalue, etb = einfo |
---|
194 | n/a | if isinstance(etype, type): |
---|
195 | n/a | etype = etype.__name__ |
---|
196 | n/a | pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable |
---|
197 | n/a | date = time.ctime(time.time()) |
---|
198 | n/a | head = "%s\n%s\n%s\n" % (str(etype), pyver, date) + ''' |
---|
199 | n/a | A problem occurred in a Python script. Here is the sequence of |
---|
200 | n/a | function calls leading up to the error, in the order they occurred. |
---|
201 | n/a | ''' |
---|
202 | n/a | |
---|
203 | n/a | frames = [] |
---|
204 | n/a | records = inspect.getinnerframes(etb, context) |
---|
205 | n/a | for frame, file, lnum, func, lines, index in records: |
---|
206 | n/a | file = file and os.path.abspath(file) or '?' |
---|
207 | n/a | args, varargs, varkw, locals = inspect.getargvalues(frame) |
---|
208 | n/a | call = '' |
---|
209 | n/a | if func != '?': |
---|
210 | n/a | call = 'in ' + func + \ |
---|
211 | n/a | inspect.formatargvalues(args, varargs, varkw, locals, |
---|
212 | n/a | formatvalue=lambda value: '=' + pydoc.text.repr(value)) |
---|
213 | n/a | |
---|
214 | n/a | highlight = {} |
---|
215 | n/a | def reader(lnum=[lnum]): |
---|
216 | n/a | highlight[lnum[0]] = 1 |
---|
217 | n/a | try: return linecache.getline(file, lnum[0]) |
---|
218 | n/a | finally: lnum[0] += 1 |
---|
219 | n/a | vars = scanvars(reader, frame, locals) |
---|
220 | n/a | |
---|
221 | n/a | rows = [' %s %s' % (file, call)] |
---|
222 | n/a | if index is not None: |
---|
223 | n/a | i = lnum - index |
---|
224 | n/a | for line in lines: |
---|
225 | n/a | num = '%5d ' % i |
---|
226 | n/a | rows.append(num+line.rstrip()) |
---|
227 | n/a | i += 1 |
---|
228 | n/a | |
---|
229 | n/a | done, dump = {}, [] |
---|
230 | n/a | for name, where, value in vars: |
---|
231 | n/a | if name in done: continue |
---|
232 | n/a | done[name] = 1 |
---|
233 | n/a | if value is not __UNDEF__: |
---|
234 | n/a | if where == 'global': name = 'global ' + name |
---|
235 | n/a | elif where != 'local': name = where + name.split('.')[-1] |
---|
236 | n/a | dump.append('%s = %s' % (name, pydoc.text.repr(value))) |
---|
237 | n/a | else: |
---|
238 | n/a | dump.append(name + ' undefined') |
---|
239 | n/a | |
---|
240 | n/a | rows.append('\n'.join(dump)) |
---|
241 | n/a | frames.append('\n%s\n' % '\n'.join(rows)) |
---|
242 | n/a | |
---|
243 | n/a | exception = ['%s: %s' % (str(etype), str(evalue))] |
---|
244 | n/a | for name in dir(evalue): |
---|
245 | n/a | value = pydoc.text.repr(getattr(evalue, name)) |
---|
246 | n/a | exception.append('\n%s%s = %s' % (" "*4, name, value)) |
---|
247 | n/a | |
---|
248 | n/a | return head + ''.join(frames) + ''.join(exception) + ''' |
---|
249 | n/a | |
---|
250 | n/a | The above is a description of an error in a Python program. Here is |
---|
251 | n/a | the original traceback: |
---|
252 | n/a | |
---|
253 | n/a | %s |
---|
254 | n/a | ''' % ''.join(traceback.format_exception(etype, evalue, etb)) |
---|
255 | n/a | |
---|
256 | n/a | class Hook: |
---|
257 | n/a | """A hook to replace sys.excepthook that shows tracebacks in HTML.""" |
---|
258 | n/a | |
---|
259 | n/a | def __init__(self, display=1, logdir=None, context=5, file=None, |
---|
260 | n/a | format="html"): |
---|
261 | n/a | self.display = display # send tracebacks to browser if true |
---|
262 | n/a | self.logdir = logdir # log tracebacks to files if not None |
---|
263 | n/a | self.context = context # number of source code lines per frame |
---|
264 | n/a | self.file = file or sys.stdout # place to send the output |
---|
265 | n/a | self.format = format |
---|
266 | n/a | |
---|
267 | n/a | def __call__(self, etype, evalue, etb): |
---|
268 | n/a | self.handle((etype, evalue, etb)) |
---|
269 | n/a | |
---|
270 | n/a | def handle(self, info=None): |
---|
271 | n/a | info = info or sys.exc_info() |
---|
272 | n/a | if self.format == "html": |
---|
273 | n/a | self.file.write(reset()) |
---|
274 | n/a | |
---|
275 | n/a | formatter = (self.format=="html") and html or text |
---|
276 | n/a | plain = False |
---|
277 | n/a | try: |
---|
278 | n/a | doc = formatter(info, self.context) |
---|
279 | n/a | except: # just in case something goes wrong |
---|
280 | n/a | doc = ''.join(traceback.format_exception(*info)) |
---|
281 | n/a | plain = True |
---|
282 | n/a | |
---|
283 | n/a | if self.display: |
---|
284 | n/a | if plain: |
---|
285 | n/a | doc = doc.replace('&', '&').replace('<', '<') |
---|
286 | n/a | self.file.write('<pre>' + doc + '</pre>\n') |
---|
287 | n/a | else: |
---|
288 | n/a | self.file.write(doc + '\n') |
---|
289 | n/a | else: |
---|
290 | n/a | self.file.write('<p>A problem occurred in a Python script.\n') |
---|
291 | n/a | |
---|
292 | n/a | if self.logdir is not None: |
---|
293 | n/a | suffix = ['.txt', '.html'][self.format=="html"] |
---|
294 | n/a | (fd, path) = tempfile.mkstemp(suffix=suffix, dir=self.logdir) |
---|
295 | n/a | |
---|
296 | n/a | try: |
---|
297 | n/a | with os.fdopen(fd, 'w') as file: |
---|
298 | n/a | file.write(doc) |
---|
299 | n/a | msg = '%s contains the description of this error.' % path |
---|
300 | n/a | except: |
---|
301 | n/a | msg = 'Tried to save traceback to %s, but failed.' % path |
---|
302 | n/a | |
---|
303 | n/a | if self.format == 'html': |
---|
304 | n/a | self.file.write('<p>%s</p>\n' % msg) |
---|
305 | n/a | else: |
---|
306 | n/a | self.file.write(msg + '\n') |
---|
307 | n/a | try: |
---|
308 | n/a | self.file.flush() |
---|
309 | n/a | except: pass |
---|
310 | n/a | |
---|
311 | n/a | handler = Hook().handle |
---|
312 | n/a | def enable(display=1, logdir=None, context=5, format="html"): |
---|
313 | n/a | """Install an exception handler that formats tracebacks as HTML. |
---|
314 | n/a | |
---|
315 | n/a | The optional argument 'display' can be set to 0 to suppress sending the |
---|
316 | n/a | traceback to the browser, and 'logdir' can be set to a directory to cause |
---|
317 | n/a | tracebacks to be written to files there.""" |
---|
318 | n/a | sys.excepthook = Hook(display=display, logdir=logdir, |
---|
319 | n/a | context=context, format=format) |
---|