blob: b0055111957e397c00ac1761fc13a66860399d84 [file] [log] [blame]
Skip Montanaro364ca402003-06-17 12:58:31 +00001"""More comprehensive traceback formatting for Python scripts.
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +00002
3To enable this module, do:
4
5 import cgitb; cgitb.enable()
6
Skip Montanaro364ca402003-06-17 12:58:31 +00007at the top of your script. The optional arguments to enable() are:
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +00008
9 display - if true, tracebacks are displayed in the web browser
10 logdir - if set, tracebacks are written to files in this directory
Ka-Ping Yee83205972001-08-21 06:53:01 +000011 context - number of lines of source code to show for each stack frame
Tim Peters478c1052003-06-29 05:46:54 +000012 format - 'text' or 'html' controls the output format
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +000013
Skip Montanaro364ca402003-06-17 12:58:31 +000014By default, tracebacks are displayed but not saved, the context is 5 lines
15and the output format is 'html' (for backwards compatibility with the
16original use of this module)
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +000017
18Alternatively, if you have caught an exception and want cgitb to display it
Skip Montanaro364ca402003-06-17 12:58:31 +000019for you, call cgitb.handler(). The optional argument to handler() is a
203-item tuple (etype, evalue, etb) just like the value of sys.exc_info().
21The default handler displays output as HTML.
22"""
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +000023
24__author__ = 'Ka-Ping Yee'
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000025
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +000026__version__ = '$Revision$'
27
Ka-Ping Yeefa78d0f2001-12-04 18:45:17 +000028import sys
29
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +000030def reset():
31 """Return a string that resets the CGI and browser to a known state."""
32 return '''<!--: spam
33Content-Type: text/html
34
Ka-Ping Yee83205972001-08-21 06:53:01 +000035<body bgcolor="#f0f0f8"><font color="#f0f0f8" size="-5"> -->
36<body bgcolor="#f0f0f8"><font color="#f0f0f8" size="-5"> --> -->
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +000037</font> </font> </font> </script> </object> </blockquote> </pre>
38</table> </table> </table> </table> </table> </font> </font> </font>'''
39
Ka-Ping Yee83205972001-08-21 06:53:01 +000040__UNDEF__ = [] # a special sentinel object
Andrew M. Kuchling5fcefdb2004-07-10 14:14:51 +000041def small(text):
42 if text:
43 return '<small>' + text + '</small>'
44 else:
45 return ''
Tim Peters182b5ac2004-07-18 06:16:08 +000046
Andrew M. Kuchling5fcefdb2004-07-10 14:14:51 +000047def strong(text):
48 if text:
49 return '<strong>' + text + '</strong>'
50 else:
51 return ''
Tim Peters182b5ac2004-07-18 06:16:08 +000052
Andrew M. Kuchling5fcefdb2004-07-10 14:14:51 +000053def grey(text):
54 if text:
55 return '<font color="#909090">' + text + '</font>'
56 else:
57 return ''
Ka-Ping Yee83205972001-08-21 06:53:01 +000058
59def lookup(name, frame, locals):
60 """Find the value for a given name in the given environment."""
61 if name in locals:
62 return 'local', locals[name]
63 if name in frame.f_globals:
64 return 'global', frame.f_globals[name]
Ka-Ping Yee711cad72002-06-26 07:10:56 +000065 if '__builtins__' in frame.f_globals:
66 builtins = frame.f_globals['__builtins__']
67 if type(builtins) is type({}):
68 if name in builtins:
69 return 'builtin', builtins[name]
70 else:
71 if hasattr(builtins, name):
72 return 'builtin', getattr(builtins, name)
Ka-Ping Yee83205972001-08-21 06:53:01 +000073 return None, __UNDEF__
74
75def scanvars(reader, frame, locals):
76 """Scan one logical line of Python and look up values of variables used."""
77 import tokenize, keyword
Andrew M. Kuchling26f6bdf2004-06-05 19:15:34 +000078 vars, lasttoken, parent, prefix, value = [], None, None, '', __UNDEF__
Ka-Ping Yee83205972001-08-21 06:53:01 +000079 for ttype, token, start, end, line in tokenize.generate_tokens(reader):
80 if ttype == tokenize.NEWLINE: break
81 if ttype == tokenize.NAME and token not in keyword.kwlist:
82 if lasttoken == '.':
83 if parent is not __UNDEF__:
84 value = getattr(parent, token, __UNDEF__)
85 vars.append((prefix + token, prefix, value))
86 else:
87 where, value = lookup(token, frame, locals)
88 vars.append((token, where, value))
89 elif token == '.':
90 prefix += lasttoken + '.'
91 parent = value
92 else:
93 parent, prefix = None, ''
94 lasttoken = token
95 return vars
96
Guido van Rossum1bc535d2007-05-15 18:46:22 +000097def html(einfo, context=5):
Ka-Ping Yee83205972001-08-21 06:53:01 +000098 """Return a nice HTML document describing a given traceback."""
Guido van Rossum13257902007-06-07 23:15:56 +000099 import os, time, traceback, linecache, inspect, pydoc
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000100
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000101 etype, evalue, etb = einfo
Guido van Rossum13257902007-06-07 23:15:56 +0000102 if isinstance(etype, type):
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000103 etype = etype.__name__
104 pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
105 date = time.ctime(time.time())
Ka-Ping Yee83205972001-08-21 06:53:01 +0000106 head = '<body bgcolor="#f0f0f8">' + pydoc.html.heading(
Andrew M. Kuchling5fcefdb2004-07-10 14:14:51 +0000107 '<big><big>%s</big></big>' %
108 strong(pydoc.html.escape(str(etype))),
Ka-Ping Yee83205972001-08-21 06:53:01 +0000109 '#ffffff', '#6622aa', pyver + '<br>' + date) + '''
110<p>A problem occurred in a Python script. Here is the sequence of
Andrew M. Kuchling5fcefdb2004-07-10 14:14:51 +0000111function calls leading up to the error, in the order they occurred.</p>'''
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000112
Ka-Ping Yee83205972001-08-21 06:53:01 +0000113 indent = '<tt>' + small('&nbsp;' * 5) + '&nbsp;</tt>'
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000114 frames = []
115 records = inspect.getinnerframes(etb, context)
116 for frame, file, lnum, func, lines, index in records:
Georg Brandl07c81d92005-06-26 21:57:55 +0000117 if file:
118 file = os.path.abspath(file)
119 link = '<a href="file://%s">%s</a>' % (file, pydoc.html.escape(file))
120 else:
121 file = link = '?'
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000122 args, varargs, varkw, locals = inspect.getargvalues(frame)
Ka-Ping Yee83205972001-08-21 06:53:01 +0000123 call = ''
124 if func != '?':
125 call = 'in ' + strong(func) + \
126 inspect.formatargvalues(args, varargs, varkw, locals,
127 formatvalue=lambda value: '=' + pydoc.html.repr(value))
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000128
Ka-Ping Yee83205972001-08-21 06:53:01 +0000129 highlight = {}
130 def reader(lnum=[lnum]):
131 highlight[lnum[0]] = 1
132 try: return linecache.getline(file, lnum[0])
133 finally: lnum[0] += 1
134 vars = scanvars(reader, frame, locals)
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000135
Ka-Ping Yee83205972001-08-21 06:53:01 +0000136 rows = ['<tr><td bgcolor="#d8bbff">%s%s %s</td></tr>' %
137 ('<big>&nbsp;</big>', link, call)]
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000138 if index is not None:
139 i = lnum - index
140 for line in lines:
Ka-Ping Yee83205972001-08-21 06:53:01 +0000141 num = small('&nbsp;' * (5-len(str(i))) + str(i)) + '&nbsp;'
142 line = '<tt>%s%s</tt>' % (num, pydoc.html.preformat(line))
143 if i in highlight:
144 rows.append('<tr><td bgcolor="#ffccee">%s</td></tr>' % line)
145 else:
146 rows.append('<tr><td>%s</td></tr>' % grey(line))
147 i += 1
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000148
Ka-Ping Yee83205972001-08-21 06:53:01 +0000149 done, dump = {}, []
150 for name, where, value in vars:
151 if name in done: continue
152 done[name] = 1
153 if value is not __UNDEF__:
Raymond Hettingerdbecd932005-02-06 06:57:08 +0000154 if where in ('global', 'builtin'):
Ka-Ping Yee711cad72002-06-26 07:10:56 +0000155 name = ('<em>%s</em> ' % where) + strong(name)
156 elif where == 'local':
157 name = strong(name)
158 else:
159 name = where + strong(name.split('.')[-1])
Ka-Ping Yee83205972001-08-21 06:53:01 +0000160 dump.append('%s&nbsp;= %s' % (name, pydoc.html.repr(value)))
161 else:
162 dump.append(name + ' <em>undefined</em>')
163
164 rows.append('<tr><td>%s</td></tr>' % small(grey(', '.join(dump))))
Andrew M. Kuchling5fcefdb2004-07-10 14:14:51 +0000165 frames.append('''
Ka-Ping Yee83205972001-08-21 06:53:01 +0000166<table width="100%%" cellspacing=0 cellpadding=0 border=0>
167%s</table>''' % '\n'.join(rows))
168
Andrew M. Kuchlingb67c9432004-03-31 20:17:56 +0000169 exception = ['<p>%s: %s' % (strong(pydoc.html.escape(str(etype))),
170 pydoc.html.escape(str(evalue)))]
Georg Brandl57b39e02007-04-11 19:24:50 +0000171 for name in dir(evalue):
172 if name[:1] == '_': continue
173 value = pydoc.html.repr(getattr(evalue, name))
174 exception.append('\n<br>%s%s&nbsp;=\n%s' % (indent, name, value))
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000175
176 import traceback
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000177 return head + ''.join(frames) + ''.join(exception) + '''
178
179
Ka-Ping Yee83205972001-08-21 06:53:01 +0000180<!-- The above is a description of an error in a Python program, formatted
181 for a Web browser because the 'cgitb' module was enabled. In case you
182 are not reading this in a Web browser, here is the original traceback:
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000183
184%s
185-->
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000186''' % pydoc.html.escape(
187 ''.join(traceback.format_exception(etype, evalue, etb)))
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000188
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000189def text(einfo, context=5):
Skip Montanaro364ca402003-06-17 12:58:31 +0000190 """Return a plain text document describing a given traceback."""
Guido van Rossum13257902007-06-07 23:15:56 +0000191 import os, time, traceback, linecache, inspect, pydoc
Skip Montanaro364ca402003-06-17 12:58:31 +0000192
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000193 etype, evalue, etb = einfo
Guido van Rossum13257902007-06-07 23:15:56 +0000194 if isinstance(etype, type):
Skip Montanaro364ca402003-06-17 12:58:31 +0000195 etype = etype.__name__
196 pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
197 date = time.ctime(time.time())
198 head = "%s\n%s\n%s\n" % (str(etype), pyver, date) + '''
199A problem occurred in a Python script. Here is the sequence of
200function calls leading up to the error, in the order they occurred.
201'''
202
203 frames = []
204 records = inspect.getinnerframes(etb, context)
205 for frame, file, lnum, func, lines, index in records:
206 file = file and os.path.abspath(file) or '?'
207 args, varargs, varkw, locals = inspect.getargvalues(frame)
208 call = ''
209 if func != '?':
210 call = 'in ' + func + \
211 inspect.formatargvalues(args, varargs, varkw, locals,
212 formatvalue=lambda value: '=' + pydoc.text.repr(value))
213
214 highlight = {}
215 def reader(lnum=[lnum]):
216 highlight[lnum[0]] = 1
217 try: return linecache.getline(file, lnum[0])
218 finally: lnum[0] += 1
219 vars = scanvars(reader, frame, locals)
220
221 rows = [' %s %s' % (file, call)]
222 if index is not None:
223 i = lnum - index
224 for line in lines:
225 num = '%5d ' % i
226 rows.append(num+line.rstrip())
227 i += 1
228
229 done, dump = {}, []
230 for name, where, value in vars:
231 if name in done: continue
232 done[name] = 1
233 if value is not __UNDEF__:
234 if where == 'global': name = 'global ' + name
Skip Montanaro1c0228a2004-06-07 11:20:40 +0000235 elif where != 'local': name = where + name.split('.')[-1]
Skip Montanaro364ca402003-06-17 12:58:31 +0000236 dump.append('%s = %s' % (name, pydoc.text.repr(value)))
237 else:
238 dump.append(name + ' undefined')
239
240 rows.append('\n'.join(dump))
241 frames.append('\n%s\n' % '\n'.join(rows))
242
243 exception = ['%s: %s' % (str(etype), str(evalue))]
Georg Brandl57b39e02007-04-11 19:24:50 +0000244 for name in dir(evalue):
245 value = pydoc.text.repr(getattr(evalue, name))
246 exception.append('\n%s%s = %s' % (" "*4, name, value))
Skip Montanaro364ca402003-06-17 12:58:31 +0000247
248 import traceback
249 return head + ''.join(frames) + ''.join(exception) + '''
250
251The above is a description of an error in a Python program. Here is
252the original traceback:
253
254%s
255''' % ''.join(traceback.format_exception(etype, evalue, etb))
256
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000257class Hook:
Ka-Ping Yee83205972001-08-21 06:53:01 +0000258 """A hook to replace sys.excepthook that shows tracebacks in HTML."""
259
Skip Montanaro364ca402003-06-17 12:58:31 +0000260 def __init__(self, display=1, logdir=None, context=5, file=None,
261 format="html"):
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000262 self.display = display # send tracebacks to browser if true
263 self.logdir = logdir # log tracebacks to files if not None
Ka-Ping Yee83205972001-08-21 06:53:01 +0000264 self.context = context # number of source code lines per frame
Ka-Ping Yeefa78d0f2001-12-04 18:45:17 +0000265 self.file = file or sys.stdout # place to send the output
Skip Montanaro364ca402003-06-17 12:58:31 +0000266 self.format = format
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000267
268 def __call__(self, etype, evalue, etb):
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000269 self.handle((etype, evalue, etb))
270
271 def handle(self, info=None):
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000272 info = info or sys.exc_info()
Skip Montanaro364ca402003-06-17 12:58:31 +0000273 if self.format == "html":
274 self.file.write(reset())
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000275
Skip Montanaro364ca402003-06-17 12:58:31 +0000276 formatter = (self.format=="html") and html or text
277 plain = False
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000278 try:
Skip Montanaro364ca402003-06-17 12:58:31 +0000279 doc = formatter(info, self.context)
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000280 except: # just in case something goes wrong
281 import traceback
Skip Montanaro364ca402003-06-17 12:58:31 +0000282 doc = ''.join(traceback.format_exception(*info))
283 plain = True
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000284
285 if self.display:
Skip Montanaro364ca402003-06-17 12:58:31 +0000286 if plain:
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000287 doc = doc.replace('&', '&amp;').replace('<', '&lt;')
Ka-Ping Yeefa78d0f2001-12-04 18:45:17 +0000288 self.file.write('<pre>' + doc + '</pre>\n')
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000289 else:
Ka-Ping Yeefa78d0f2001-12-04 18:45:17 +0000290 self.file.write(doc + '\n')
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000291 else:
Ka-Ping Yeefa78d0f2001-12-04 18:45:17 +0000292 self.file.write('<p>A problem occurred in a Python script.\n')
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000293
294 if self.logdir is not None:
Ka-Ping Yee83205972001-08-21 06:53:01 +0000295 import os, tempfile
Andrew M. Kuchling30633c92004-05-06 13:13:44 +0000296 suffix = ['.txt', '.html'][self.format=="html"]
Skip Montanaro364ca402003-06-17 12:58:31 +0000297 (fd, path) = tempfile.mkstemp(suffix=suffix, dir=self.logdir)
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000298 try:
Guido van Rossum3b0a3292002-08-09 16:38:32 +0000299 file = os.fdopen(fd, 'w')
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000300 file.write(doc)
301 file.close()
Ka-Ping Yeefa78d0f2001-12-04 18:45:17 +0000302 msg = '<p> %s contains the description of this error.' % path
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000303 except:
Ka-Ping Yeefa78d0f2001-12-04 18:45:17 +0000304 msg = '<p> Tried to save traceback to %s, but failed.' % path
305 self.file.write(msg + '\n')
306 try:
307 self.file.flush()
308 except: pass
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000309
310handler = Hook().handle
Skip Montanaro364ca402003-06-17 12:58:31 +0000311def enable(display=1, logdir=None, context=5, format="html"):
Ka-Ping Yee83205972001-08-21 06:53:01 +0000312 """Install an exception handler that formats tracebacks as HTML.
313
314 The optional argument 'display' can be set to 0 to suppress sending the
315 traceback to the browser, and 'logdir' can be set to a directory to cause
316 tracebacks to be written to files there."""
Skip Montanaro364ca402003-06-17 12:58:31 +0000317 sys.excepthook = Hook(display=display, logdir=logdir,
318 context=context, format=format)