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