blob: db46b25d60b5c76737bdfff2f474959d25b83d8b [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'
25__version__ = '$Revision$'
26
Ka-Ping Yeefa78d0f2001-12-04 18:45:17 +000027import sys
28
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +000029def reset():
30 """Return a string that resets the CGI and browser to a known state."""
31 return '''<!--: spam
32Content-Type: text/html
33
Ka-Ping Yee83205972001-08-21 06:53:01 +000034<body bgcolor="#f0f0f8"><font color="#f0f0f8" size="-5"> -->
35<body bgcolor="#f0f0f8"><font color="#f0f0f8" size="-5"> --> -->
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +000036</font> </font> </font> </script> </object> </blockquote> </pre>
37</table> </table> </table> </table> </table> </font> </font> </font>'''
38
Ka-Ping Yee83205972001-08-21 06:53:01 +000039__UNDEF__ = [] # a special sentinel object
Andrew M. Kuchling5fcefdb2004-07-10 14:14:51 +000040def small(text):
41 if text:
42 return '<small>' + text + '</small>'
43 else:
44 return ''
Tim Peters182b5ac2004-07-18 06:16:08 +000045
Andrew M. Kuchling5fcefdb2004-07-10 14:14:51 +000046def strong(text):
47 if text:
48 return '<strong>' + text + '</strong>'
49 else:
50 return ''
Tim Peters182b5ac2004-07-18 06:16:08 +000051
Andrew M. Kuchling5fcefdb2004-07-10 14:14:51 +000052def grey(text):
53 if text:
54 return '<font color="#909090">' + text + '</font>'
55 else:
56 return ''
Ka-Ping Yee83205972001-08-21 06:53:01 +000057
58def lookup(name, frame, locals):
59 """Find the value for a given name in the given environment."""
60 if name in locals:
61 return 'local', locals[name]
62 if name in frame.f_globals:
63 return 'global', frame.f_globals[name]
Ka-Ping Yee711cad72002-06-26 07:10:56 +000064 if '__builtins__' in frame.f_globals:
65 builtins = frame.f_globals['__builtins__']
66 if type(builtins) is type({}):
67 if name in builtins:
68 return 'builtin', builtins[name]
69 else:
70 if hasattr(builtins, name):
71 return 'builtin', getattr(builtins, name)
Ka-Ping Yee83205972001-08-21 06:53:01 +000072 return None, __UNDEF__
73
74def scanvars(reader, frame, locals):
75 """Scan one logical line of Python and look up values of variables used."""
76 import tokenize, keyword
Andrew M. Kuchling26f6bdf2004-06-05 19:15:34 +000077 vars, lasttoken, parent, prefix, value = [], None, None, '', __UNDEF__
Ka-Ping Yee83205972001-08-21 06:53:01 +000078 for ttype, token, start, end, line in tokenize.generate_tokens(reader):
79 if ttype == tokenize.NEWLINE: break
80 if ttype == tokenize.NAME and token not in keyword.kwlist:
81 if lasttoken == '.':
82 if parent is not __UNDEF__:
83 value = getattr(parent, token, __UNDEF__)
84 vars.append((prefix + token, prefix, value))
85 else:
86 where, value = lookup(token, frame, locals)
87 vars.append((token, where, value))
88 elif token == '.':
89 prefix += lasttoken + '.'
90 parent = value
91 else:
92 parent, prefix = None, ''
93 lasttoken = token
94 return vars
95
96def html((etype, evalue, etb), context=5):
97 """Return a nice HTML document describing a given traceback."""
Ka-Ping Yeefa78d0f2001-12-04 18:45:17 +000098 import os, types, time, traceback, linecache, inspect, pydoc
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +000099
100 if type(etype) is types.ClassType:
101 etype = etype.__name__
102 pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
103 date = time.ctime(time.time())
Ka-Ping Yee83205972001-08-21 06:53:01 +0000104 head = '<body bgcolor="#f0f0f8">' + pydoc.html.heading(
Andrew M. Kuchling5fcefdb2004-07-10 14:14:51 +0000105 '<big><big>%s</big></big>' %
106 strong(pydoc.html.escape(str(etype))),
Ka-Ping Yee83205972001-08-21 06:53:01 +0000107 '#ffffff', '#6622aa', pyver + '<br>' + date) + '''
108<p>A problem occurred in a Python script. Here is the sequence of
Andrew M. Kuchling5fcefdb2004-07-10 14:14:51 +0000109function calls leading up to the error, in the order they occurred.</p>'''
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000110
Ka-Ping Yee83205972001-08-21 06:53:01 +0000111 indent = '<tt>' + small('&nbsp;' * 5) + '&nbsp;</tt>'
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000112 frames = []
113 records = inspect.getinnerframes(etb, context)
114 for frame, file, lnum, func, lines, index in records:
115 file = file and os.path.abspath(file) or '?'
Ka-Ping Yee83205972001-08-21 06:53:01 +0000116 link = '<a href="file://%s">%s</a>' % (file, pydoc.html.escape(file))
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000117 args, varargs, varkw, locals = inspect.getargvalues(frame)
Ka-Ping Yee83205972001-08-21 06:53:01 +0000118 call = ''
119 if func != '?':
120 call = 'in ' + strong(func) + \
121 inspect.formatargvalues(args, varargs, varkw, locals,
122 formatvalue=lambda value: '=' + pydoc.html.repr(value))
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000123
Ka-Ping Yee83205972001-08-21 06:53:01 +0000124 highlight = {}
125 def reader(lnum=[lnum]):
126 highlight[lnum[0]] = 1
127 try: return linecache.getline(file, lnum[0])
128 finally: lnum[0] += 1
129 vars = scanvars(reader, frame, locals)
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000130
Ka-Ping Yee83205972001-08-21 06:53:01 +0000131 rows = ['<tr><td bgcolor="#d8bbff">%s%s %s</td></tr>' %
132 ('<big>&nbsp;</big>', link, call)]
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000133 if index is not None:
134 i = lnum - index
135 for line in lines:
Ka-Ping Yee83205972001-08-21 06:53:01 +0000136 num = small('&nbsp;' * (5-len(str(i))) + str(i)) + '&nbsp;'
137 line = '<tt>%s%s</tt>' % (num, pydoc.html.preformat(line))
138 if i in highlight:
139 rows.append('<tr><td bgcolor="#ffccee">%s</td></tr>' % line)
140 else:
141 rows.append('<tr><td>%s</td></tr>' % grey(line))
142 i += 1
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000143
Ka-Ping Yee83205972001-08-21 06:53:01 +0000144 done, dump = {}, []
145 for name, where, value in vars:
146 if name in done: continue
147 done[name] = 1
148 if value is not __UNDEF__:
Ka-Ping Yee711cad72002-06-26 07:10:56 +0000149 if where in ['global', 'builtin']:
150 name = ('<em>%s</em> ' % where) + strong(name)
151 elif where == 'local':
152 name = strong(name)
153 else:
154 name = where + strong(name.split('.')[-1])
Ka-Ping Yee83205972001-08-21 06:53:01 +0000155 dump.append('%s&nbsp;= %s' % (name, pydoc.html.repr(value)))
156 else:
157 dump.append(name + ' <em>undefined</em>')
158
159 rows.append('<tr><td>%s</td></tr>' % small(grey(', '.join(dump))))
Andrew M. Kuchling5fcefdb2004-07-10 14:14:51 +0000160 frames.append('''
Ka-Ping Yee83205972001-08-21 06:53:01 +0000161<table width="100%%" cellspacing=0 cellpadding=0 border=0>
162%s</table>''' % '\n'.join(rows))
163
Andrew M. Kuchlingb67c9432004-03-31 20:17:56 +0000164 exception = ['<p>%s: %s' % (strong(pydoc.html.escape(str(etype))),
165 pydoc.html.escape(str(evalue)))]
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000166 if type(evalue) is types.InstanceType:
167 for name in dir(evalue):
Ka-Ping Yee711cad72002-06-26 07:10:56 +0000168 if name[:1] == '_': continue
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000169 value = pydoc.html.repr(getattr(evalue, name))
170 exception.append('\n<br>%s%s&nbsp;=\n%s' % (indent, name, value))
171
172 import traceback
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000173 return head + ''.join(frames) + ''.join(exception) + '''
174
175
Ka-Ping Yee83205972001-08-21 06:53:01 +0000176<!-- The above is a description of an error in a Python program, formatted
177 for a Web browser because the 'cgitb' module was enabled. In case you
178 are not reading this in a Web browser, here is the original traceback:
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000179
180%s
181-->
Ka-Ping Yee83205972001-08-21 06:53:01 +0000182''' % ''.join(traceback.format_exception(etype, evalue, etb))
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000183
Skip Montanaro364ca402003-06-17 12:58:31 +0000184def text((etype, evalue, etb), context=5):
185 """Return a plain text document describing a given traceback."""
186 import os, types, time, traceback, linecache, inspect, pydoc
187
188 if type(etype) is types.ClassType:
189 etype = etype.__name__
190 pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
191 date = time.ctime(time.time())
192 head = "%s\n%s\n%s\n" % (str(etype), pyver, date) + '''
193A problem occurred in a Python script. Here is the sequence of
194function calls leading up to the error, in the order they occurred.
195'''
196
197 frames = []
198 records = inspect.getinnerframes(etb, context)
199 for frame, file, lnum, func, lines, index in records:
200 file = file and os.path.abspath(file) or '?'
201 args, varargs, varkw, locals = inspect.getargvalues(frame)
202 call = ''
203 if func != '?':
204 call = 'in ' + func + \
205 inspect.formatargvalues(args, varargs, varkw, locals,
206 formatvalue=lambda value: '=' + pydoc.text.repr(value))
207
208 highlight = {}
209 def reader(lnum=[lnum]):
210 highlight[lnum[0]] = 1
211 try: return linecache.getline(file, lnum[0])
212 finally: lnum[0] += 1
213 vars = scanvars(reader, frame, locals)
214
215 rows = [' %s %s' % (file, call)]
216 if index is not None:
217 i = lnum - index
218 for line in lines:
219 num = '%5d ' % i
220 rows.append(num+line.rstrip())
221 i += 1
222
223 done, dump = {}, []
224 for name, where, value in vars:
225 if name in done: continue
226 done[name] = 1
227 if value is not __UNDEF__:
228 if where == 'global': name = 'global ' + name
Skip Montanaro1c0228a2004-06-07 11:20:40 +0000229 elif where != 'local': name = where + name.split('.')[-1]
Skip Montanaro364ca402003-06-17 12:58:31 +0000230 dump.append('%s = %s' % (name, pydoc.text.repr(value)))
231 else:
232 dump.append(name + ' undefined')
233
234 rows.append('\n'.join(dump))
235 frames.append('\n%s\n' % '\n'.join(rows))
236
237 exception = ['%s: %s' % (str(etype), str(evalue))]
238 if type(evalue) is types.InstanceType:
239 for name in dir(evalue):
240 value = pydoc.text.repr(getattr(evalue, name))
241 exception.append('\n%s%s = %s' % (" "*4, name, value))
242
243 import traceback
244 return head + ''.join(frames) + ''.join(exception) + '''
245
246The above is a description of an error in a Python program. Here is
247the original traceback:
248
249%s
250''' % ''.join(traceback.format_exception(etype, evalue, etb))
251
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000252class Hook:
Ka-Ping Yee83205972001-08-21 06:53:01 +0000253 """A hook to replace sys.excepthook that shows tracebacks in HTML."""
254
Skip Montanaro364ca402003-06-17 12:58:31 +0000255 def __init__(self, display=1, logdir=None, context=5, file=None,
256 format="html"):
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000257 self.display = display # send tracebacks to browser if true
258 self.logdir = logdir # log tracebacks to files if not None
Ka-Ping Yee83205972001-08-21 06:53:01 +0000259 self.context = context # number of source code lines per frame
Ka-Ping Yeefa78d0f2001-12-04 18:45:17 +0000260 self.file = file or sys.stdout # place to send the output
Skip Montanaro364ca402003-06-17 12:58:31 +0000261 self.format = format
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000262
263 def __call__(self, etype, evalue, etb):
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000264 self.handle((etype, evalue, etb))
265
266 def handle(self, info=None):
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000267 info = info or sys.exc_info()
Skip Montanaro364ca402003-06-17 12:58:31 +0000268 if self.format == "html":
269 self.file.write(reset())
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000270
Skip Montanaro364ca402003-06-17 12:58:31 +0000271 formatter = (self.format=="html") and html or text
272 plain = False
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000273 try:
Skip Montanaro364ca402003-06-17 12:58:31 +0000274 doc = formatter(info, self.context)
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000275 except: # just in case something goes wrong
276 import traceback
Skip Montanaro364ca402003-06-17 12:58:31 +0000277 doc = ''.join(traceback.format_exception(*info))
278 plain = True
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000279
280 if self.display:
Skip Montanaro364ca402003-06-17 12:58:31 +0000281 if plain:
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000282 doc = doc.replace('&', '&amp;').replace('<', '&lt;')
Ka-Ping Yeefa78d0f2001-12-04 18:45:17 +0000283 self.file.write('<pre>' + doc + '</pre>\n')
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000284 else:
Ka-Ping Yeefa78d0f2001-12-04 18:45:17 +0000285 self.file.write(doc + '\n')
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000286 else:
Ka-Ping Yeefa78d0f2001-12-04 18:45:17 +0000287 self.file.write('<p>A problem occurred in a Python script.\n')
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000288
289 if self.logdir is not None:
Ka-Ping Yee83205972001-08-21 06:53:01 +0000290 import os, tempfile
Andrew M. Kuchling30633c92004-05-06 13:13:44 +0000291 suffix = ['.txt', '.html'][self.format=="html"]
Skip Montanaro364ca402003-06-17 12:58:31 +0000292 (fd, path) = tempfile.mkstemp(suffix=suffix, dir=self.logdir)
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000293 try:
Guido van Rossum3b0a3292002-08-09 16:38:32 +0000294 file = os.fdopen(fd, 'w')
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000295 file.write(doc)
296 file.close()
Ka-Ping Yeefa78d0f2001-12-04 18:45:17 +0000297 msg = '<p> %s contains the description of this error.' % path
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000298 except:
Ka-Ping Yeefa78d0f2001-12-04 18:45:17 +0000299 msg = '<p> Tried to save traceback to %s, but failed.' % path
300 self.file.write(msg + '\n')
301 try:
302 self.file.flush()
303 except: pass
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000304
305handler = Hook().handle
Skip Montanaro364ca402003-06-17 12:58:31 +0000306def enable(display=1, logdir=None, context=5, format="html"):
Ka-Ping Yee83205972001-08-21 06:53:01 +0000307 """Install an exception handler that formats tracebacks as HTML.
308
309 The optional argument 'display' can be set to 0 to suppress sending the
310 traceback to the browser, and 'logdir' can be set to a directory to cause
311 tracebacks to be written to files there."""
Skip Montanaro364ca402003-06-17 12:58:31 +0000312 sys.excepthook = Hook(display=display, logdir=logdir,
313 context=context, format=format)