blob: 831f792e1d0d6bac92bf4cf9ab781396a0eaa246 [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.
Brett Cannonad078a02009-04-01 16:00:34 +000022
Skip Montanaro364ca402003-06-17 12:58:31 +000023"""
Brett Cannonad078a02009-04-01 16:00:34 +000024import inspect
25import keyword
26import linecache
27import os
28import pydoc
Ka-Ping Yeefa78d0f2001-12-04 18:45:17 +000029import sys
Brett Cannonad078a02009-04-01 16:00:34 +000030import tempfile
31import time
32import tokenize
33import traceback
34import types
Ka-Ping Yeefa78d0f2001-12-04 18:45:17 +000035
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +000036def reset():
37 """Return a string that resets the CGI and browser to a known state."""
38 return '''<!--: spam
39Content-Type: text/html
40
Ka-Ping Yee83205972001-08-21 06:53:01 +000041<body bgcolor="#f0f0f8"><font color="#f0f0f8" size="-5"> -->
42<body bgcolor="#f0f0f8"><font color="#f0f0f8" size="-5"> --> -->
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +000043</font> </font> </font> </script> </object> </blockquote> </pre>
44</table> </table> </table> </table> </table> </font> </font> </font>'''
45
Ka-Ping Yee83205972001-08-21 06:53:01 +000046__UNDEF__ = [] # a special sentinel object
Andrew M. Kuchling5fcefdb2004-07-10 14:14:51 +000047def small(text):
48 if text:
49 return '<small>' + text + '</small>'
50 else:
51 return ''
Tim Peters182b5ac2004-07-18 06:16:08 +000052
Andrew M. Kuchling5fcefdb2004-07-10 14:14:51 +000053def strong(text):
54 if text:
55 return '<strong>' + text + '</strong>'
56 else:
57 return ''
Tim Peters182b5ac2004-07-18 06:16:08 +000058
Andrew M. Kuchling5fcefdb2004-07-10 14:14:51 +000059def grey(text):
60 if text:
61 return '<font color="#909090">' + text + '</font>'
62 else:
63 return ''
Ka-Ping Yee83205972001-08-21 06:53:01 +000064
65def lookup(name, frame, locals):
66 """Find the value for a given name in the given environment."""
67 if name in locals:
68 return 'local', locals[name]
69 if name in frame.f_globals:
70 return 'global', frame.f_globals[name]
Ka-Ping Yee711cad72002-06-26 07:10:56 +000071 if '__builtins__' in frame.f_globals:
72 builtins = frame.f_globals['__builtins__']
73 if type(builtins) is type({}):
74 if name in builtins:
75 return 'builtin', builtins[name]
76 else:
77 if hasattr(builtins, name):
78 return 'builtin', getattr(builtins, name)
Ka-Ping Yee83205972001-08-21 06:53:01 +000079 return None, __UNDEF__
80
81def scanvars(reader, frame, locals):
82 """Scan one logical line of Python and look up values of variables used."""
Andrew M. Kuchling26f6bdf2004-06-05 19:15:34 +000083 vars, lasttoken, parent, prefix, value = [], None, None, '', __UNDEF__
Ka-Ping Yee83205972001-08-21 06:53:01 +000084 for ttype, token, start, end, line in tokenize.generate_tokens(reader):
85 if ttype == tokenize.NEWLINE: break
86 if ttype == tokenize.NAME and token not in keyword.kwlist:
87 if lasttoken == '.':
88 if parent is not __UNDEF__:
89 value = getattr(parent, token, __UNDEF__)
90 vars.append((prefix + token, prefix, value))
91 else:
92 where, value = lookup(token, frame, locals)
93 vars.append((token, where, value))
94 elif token == '.':
95 prefix += lasttoken + '.'
96 parent = value
97 else:
98 parent, prefix = None, ''
99 lasttoken = token
100 return vars
101
102def html((etype, evalue, etb), context=5):
103 """Return a nice HTML document describing a given traceback."""
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000104 if type(etype) is types.ClassType:
105 etype = etype.__name__
106 pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
107 date = time.ctime(time.time())
Ka-Ping Yee83205972001-08-21 06:53:01 +0000108 head = '<body bgcolor="#f0f0f8">' + pydoc.html.heading(
Andrew M. Kuchling5fcefdb2004-07-10 14:14:51 +0000109 '<big><big>%s</big></big>' %
110 strong(pydoc.html.escape(str(etype))),
Ka-Ping Yee83205972001-08-21 06:53:01 +0000111 '#ffffff', '#6622aa', pyver + '<br>' + date) + '''
112<p>A problem occurred in a Python script. Here is the sequence of
Andrew M. Kuchling5fcefdb2004-07-10 14:14:51 +0000113function calls leading up to the error, in the order they occurred.</p>'''
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000114
Ka-Ping Yee83205972001-08-21 06:53:01 +0000115 indent = '<tt>' + small('&nbsp;' * 5) + '&nbsp;</tt>'
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000116 frames = []
117 records = inspect.getinnerframes(etb, context)
118 for frame, file, lnum, func, lines, index in records:
Georg Brandl07c81d92005-06-26 21:57:55 +0000119 if file:
120 file = os.path.abspath(file)
121 link = '<a href="file://%s">%s</a>' % (file, pydoc.html.escape(file))
122 else:
123 file = link = '?'
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000124 args, varargs, varkw, locals = inspect.getargvalues(frame)
Ka-Ping Yee83205972001-08-21 06:53:01 +0000125 call = ''
126 if func != '?':
127 call = 'in ' + strong(func) + \
128 inspect.formatargvalues(args, varargs, varkw, locals,
129 formatvalue=lambda value: '=' + pydoc.html.repr(value))
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000130
Ka-Ping Yee83205972001-08-21 06:53:01 +0000131 highlight = {}
132 def reader(lnum=[lnum]):
133 highlight[lnum[0]] = 1
134 try: return linecache.getline(file, lnum[0])
135 finally: lnum[0] += 1
136 vars = scanvars(reader, frame, locals)
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000137
Ka-Ping Yee83205972001-08-21 06:53:01 +0000138 rows = ['<tr><td bgcolor="#d8bbff">%s%s %s</td></tr>' %
139 ('<big>&nbsp;</big>', link, call)]
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000140 if index is not None:
141 i = lnum - index
142 for line in lines:
Ka-Ping Yee83205972001-08-21 06:53:01 +0000143 num = small('&nbsp;' * (5-len(str(i))) + str(i)) + '&nbsp;'
144 line = '<tt>%s%s</tt>' % (num, pydoc.html.preformat(line))
145 if i in highlight:
146 rows.append('<tr><td bgcolor="#ffccee">%s</td></tr>' % line)
147 else:
148 rows.append('<tr><td>%s</td></tr>' % grey(line))
149 i += 1
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000150
Ka-Ping Yee83205972001-08-21 06:53:01 +0000151 done, dump = {}, []
152 for name, where, value in vars:
153 if name in done: continue
154 done[name] = 1
155 if value is not __UNDEF__:
Raymond Hettingerdbecd932005-02-06 06:57:08 +0000156 if where in ('global', 'builtin'):
Ka-Ping Yee711cad72002-06-26 07:10:56 +0000157 name = ('<em>%s</em> ' % where) + strong(name)
158 elif where == 'local':
159 name = strong(name)
160 else:
161 name = where + strong(name.split('.')[-1])
Ka-Ping Yee83205972001-08-21 06:53:01 +0000162 dump.append('%s&nbsp;= %s' % (name, pydoc.html.repr(value)))
163 else:
164 dump.append(name + ' <em>undefined</em>')
165
166 rows.append('<tr><td>%s</td></tr>' % small(grey(', '.join(dump))))
Andrew M. Kuchling5fcefdb2004-07-10 14:14:51 +0000167 frames.append('''
Ka-Ping Yee83205972001-08-21 06:53:01 +0000168<table width="100%%" cellspacing=0 cellpadding=0 border=0>
169%s</table>''' % '\n'.join(rows))
170
Andrew M. Kuchlingb67c9432004-03-31 20:17:56 +0000171 exception = ['<p>%s: %s' % (strong(pydoc.html.escape(str(etype))),
172 pydoc.html.escape(str(evalue)))]
Georg Brandl135c3172007-04-11 19:25:11 +0000173 if isinstance(evalue, BaseException):
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000174 for name in dir(evalue):
Ka-Ping Yee711cad72002-06-26 07:10:56 +0000175 if name[:1] == '_': continue
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000176 value = pydoc.html.repr(getattr(evalue, name))
177 exception.append('\n<br>%s%s&nbsp;=\n%s' % (indent, name, value))
178
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000179 return head + ''.join(frames) + ''.join(exception) + '''
180
181
Ka-Ping Yee83205972001-08-21 06:53:01 +0000182<!-- The above is a description of an error in a Python program, formatted
183 for a Web browser because the 'cgitb' module was enabled. In case you
184 are not reading this in a Web browser, here is the original traceback:
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000185
186%s
187-->
Georg Brandla09a96a2007-05-15 20:19:34 +0000188''' % pydoc.html.escape(
189 ''.join(traceback.format_exception(etype, evalue, etb)))
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000190
Skip Montanaro364ca402003-06-17 12:58:31 +0000191def text((etype, evalue, etb), context=5):
192 """Return a plain text document describing a given traceback."""
Skip Montanaro364ca402003-06-17 12:58:31 +0000193 if type(etype) is types.ClassType:
194 etype = etype.__name__
195 pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
196 date = time.ctime(time.time())
197 head = "%s\n%s\n%s\n" % (str(etype), pyver, date) + '''
198A problem occurred in a Python script. Here is the sequence of
199function calls leading up to the error, in the order they occurred.
200'''
201
202 frames = []
203 records = inspect.getinnerframes(etb, context)
204 for frame, file, lnum, func, lines, index in records:
205 file = file and os.path.abspath(file) or '?'
206 args, varargs, varkw, locals = inspect.getargvalues(frame)
207 call = ''
208 if func != '?':
209 call = 'in ' + func + \
210 inspect.formatargvalues(args, varargs, varkw, locals,
211 formatvalue=lambda value: '=' + pydoc.text.repr(value))
212
213 highlight = {}
214 def reader(lnum=[lnum]):
215 highlight[lnum[0]] = 1
216 try: return linecache.getline(file, lnum[0])
217 finally: lnum[0] += 1
218 vars = scanvars(reader, frame, locals)
219
220 rows = [' %s %s' % (file, call)]
221 if index is not None:
222 i = lnum - index
223 for line in lines:
224 num = '%5d ' % i
225 rows.append(num+line.rstrip())
226 i += 1
227
228 done, dump = {}, []
229 for name, where, value in vars:
230 if name in done: continue
231 done[name] = 1
232 if value is not __UNDEF__:
233 if where == 'global': name = 'global ' + name
Skip Montanaro1c0228a2004-06-07 11:20:40 +0000234 elif where != 'local': name = where + name.split('.')[-1]
Skip Montanaro364ca402003-06-17 12:58:31 +0000235 dump.append('%s = %s' % (name, pydoc.text.repr(value)))
236 else:
237 dump.append(name + ' undefined')
238
239 rows.append('\n'.join(dump))
240 frames.append('\n%s\n' % '\n'.join(rows))
241
242 exception = ['%s: %s' % (str(etype), str(evalue))]
Georg Brandl135c3172007-04-11 19:25:11 +0000243 if isinstance(evalue, BaseException):
Skip Montanaro364ca402003-06-17 12:58:31 +0000244 for name in dir(evalue):
245 value = pydoc.text.repr(getattr(evalue, name))
246 exception.append('\n%s%s = %s' % (" "*4, name, value))
247
Skip Montanaro364ca402003-06-17 12:58:31 +0000248 return head + ''.join(frames) + ''.join(exception) + '''
249
250The above is a description of an error in a Python program. Here is
251the original traceback:
252
253%s
254''' % ''.join(traceback.format_exception(etype, evalue, etb))
255
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000256class Hook:
Ka-Ping Yee83205972001-08-21 06:53:01 +0000257 """A hook to replace sys.excepthook that shows tracebacks in HTML."""
258
Skip Montanaro364ca402003-06-17 12:58:31 +0000259 def __init__(self, display=1, logdir=None, context=5, file=None,
260 format="html"):
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000261 self.display = display # send tracebacks to browser if true
262 self.logdir = logdir # log tracebacks to files if not None
Ka-Ping Yee83205972001-08-21 06:53:01 +0000263 self.context = context # number of source code lines per frame
Ka-Ping Yeefa78d0f2001-12-04 18:45:17 +0000264 self.file = file or sys.stdout # place to send the output
Skip Montanaro364ca402003-06-17 12:58:31 +0000265 self.format = format
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000266
267 def __call__(self, etype, evalue, etb):
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000268 self.handle((etype, evalue, etb))
269
270 def handle(self, info=None):
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000271 info = info or sys.exc_info()
Skip Montanaro364ca402003-06-17 12:58:31 +0000272 if self.format == "html":
273 self.file.write(reset())
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000274
Skip Montanaro364ca402003-06-17 12:58:31 +0000275 formatter = (self.format=="html") and html or text
276 plain = False
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000277 try:
Skip Montanaro364ca402003-06-17 12:58:31 +0000278 doc = formatter(info, self.context)
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000279 except: # just in case something goes wrong
Skip Montanaro364ca402003-06-17 12:58:31 +0000280 doc = ''.join(traceback.format_exception(*info))
281 plain = True
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000282
283 if self.display:
Skip Montanaro364ca402003-06-17 12:58:31 +0000284 if plain:
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000285 doc = doc.replace('&', '&amp;').replace('<', '&lt;')
Ka-Ping Yeefa78d0f2001-12-04 18:45:17 +0000286 self.file.write('<pre>' + doc + '</pre>\n')
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000287 else:
Ka-Ping Yeefa78d0f2001-12-04 18:45:17 +0000288 self.file.write(doc + '\n')
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000289 else:
Ka-Ping Yeefa78d0f2001-12-04 18:45:17 +0000290 self.file.write('<p>A problem occurred in a Python script.\n')
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000291
292 if self.logdir is not None:
Andrew M. Kuchling30633c92004-05-06 13:13:44 +0000293 suffix = ['.txt', '.html'][self.format=="html"]
Skip Montanaro364ca402003-06-17 12:58:31 +0000294 (fd, path) = tempfile.mkstemp(suffix=suffix, dir=self.logdir)
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000295 try:
Guido van Rossum3b0a3292002-08-09 16:38:32 +0000296 file = os.fdopen(fd, 'w')
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000297 file.write(doc)
298 file.close()
Ka-Ping Yeefa78d0f2001-12-04 18:45:17 +0000299 msg = '<p> %s contains the description of this error.' % path
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000300 except:
Ka-Ping Yeefa78d0f2001-12-04 18:45:17 +0000301 msg = '<p> Tried to save traceback to %s, but failed.' % path
302 self.file.write(msg + '\n')
303 try:
304 self.file.flush()
305 except: pass
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000306
307handler = Hook().handle
Skip Montanaro364ca402003-06-17 12:58:31 +0000308def enable(display=1, logdir=None, context=5, format="html"):
Ka-Ping Yee83205972001-08-21 06:53:01 +0000309 """Install an exception handler that formats tracebacks as HTML.
310
311 The optional argument 'display' can be set to 0 to suppress sending the
312 traceback to the browser, and 'logdir' can be set to a directory to cause
313 tracebacks to be written to files there."""
Skip Montanaro364ca402003-06-17 12:58:31 +0000314 sys.excepthook = Hook(display=display, logdir=logdir,
315 context=context, format=format)