blob: e9b0376915113b1b599efcc900602819944e6302 [file] [log] [blame]
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +00001"""Handle exceptions in CGI scripts by formatting tracebacks into nice HTML.
2
3To enable this module, do:
4
5 import cgitb; cgitb.enable()
6
7at the top of your CGI script. The optional arguments to enable() are:
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 Yee83205972001-08-21 06:53:01 +000011 context - number of lines of source code to show for each stack frame
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +000012
Ka-Ping Yee83205972001-08-21 06:53:01 +000013By default, tracebacks are displayed but not saved, and context is 5.
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +000014
15Alternatively, if you have caught an exception and want cgitb to display it
16for you, call cgitb.handle(). The optional argument to handle() is a 3-item
17tuple (etype, evalue, etb) just like the value of sys.exc_info()."""
18
19__author__ = 'Ka-Ping Yee'
20__version__ = '$Revision$'
21
22def reset():
23 """Return a string that resets the CGI and browser to a known state."""
24 return '''<!--: spam
25Content-Type: text/html
26
Ka-Ping Yee83205972001-08-21 06:53:01 +000027<body bgcolor="#f0f0f8"><font color="#f0f0f8" size="-5"> -->
28<body bgcolor="#f0f0f8"><font color="#f0f0f8" size="-5"> --> -->
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +000029</font> </font> </font> </script> </object> </blockquote> </pre>
30</table> </table> </table> </table> </table> </font> </font> </font>'''
31
Ka-Ping Yee83205972001-08-21 06:53:01 +000032__UNDEF__ = [] # a special sentinel object
33def small(text): return '<small>' + text + '</small>'
34def strong(text): return '<strong>' + text + '</strong>'
35def grey(text): return '<font color="#909090">' + text + '</font>'
36
37def lookup(name, frame, locals):
38 """Find the value for a given name in the given environment."""
39 if name in locals:
40 return 'local', locals[name]
41 if name in frame.f_globals:
42 return 'global', frame.f_globals[name]
43 return None, __UNDEF__
44
45def scanvars(reader, frame, locals):
46 """Scan one logical line of Python and look up values of variables used."""
47 import tokenize, keyword
48 vars, lasttoken, parent, prefix = [], None, None, ''
49 for ttype, token, start, end, line in tokenize.generate_tokens(reader):
50 if ttype == tokenize.NEWLINE: break
51 if ttype == tokenize.NAME and token not in keyword.kwlist:
52 if lasttoken == '.':
53 if parent is not __UNDEF__:
54 value = getattr(parent, token, __UNDEF__)
55 vars.append((prefix + token, prefix, value))
56 else:
57 where, value = lookup(token, frame, locals)
58 vars.append((token, where, value))
59 elif token == '.':
60 prefix += lasttoken + '.'
61 parent = value
62 else:
63 parent, prefix = None, ''
64 lasttoken = token
65 return vars
66
67def html((etype, evalue, etb), context=5):
68 """Return a nice HTML document describing a given traceback."""
69 import sys, os, types, time, traceback, linecache, inspect, pydoc
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +000070
71 if type(etype) is types.ClassType:
72 etype = etype.__name__
73 pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
74 date = time.ctime(time.time())
Ka-Ping Yee83205972001-08-21 06:53:01 +000075 head = '<body bgcolor="#f0f0f8">' + pydoc.html.heading(
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +000076 '<big><big><strong>%s</strong></big></big>' % str(etype),
Ka-Ping Yee83205972001-08-21 06:53:01 +000077 '#ffffff', '#6622aa', pyver + '<br>' + date) + '''
78<p>A problem occurred in a Python script. Here is the sequence of
79function calls leading up to the error, in the order they occurred.'''
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +000080
Ka-Ping Yee83205972001-08-21 06:53:01 +000081 indent = '<tt>' + small('&nbsp;' * 5) + '&nbsp;</tt>'
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +000082 frames = []
83 records = inspect.getinnerframes(etb, context)
84 for frame, file, lnum, func, lines, index in records:
85 file = file and os.path.abspath(file) or '?'
Ka-Ping Yee83205972001-08-21 06:53:01 +000086 link = '<a href="file://%s">%s</a>' % (file, pydoc.html.escape(file))
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +000087 args, varargs, varkw, locals = inspect.getargvalues(frame)
Ka-Ping Yee83205972001-08-21 06:53:01 +000088 call = ''
89 if func != '?':
90 call = 'in ' + strong(func) + \
91 inspect.formatargvalues(args, varargs, varkw, locals,
92 formatvalue=lambda value: '=' + pydoc.html.repr(value))
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +000093
Ka-Ping Yee83205972001-08-21 06:53:01 +000094 highlight = {}
95 def reader(lnum=[lnum]):
96 highlight[lnum[0]] = 1
97 try: return linecache.getline(file, lnum[0])
98 finally: lnum[0] += 1
99 vars = scanvars(reader, frame, locals)
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000100
Ka-Ping Yee83205972001-08-21 06:53:01 +0000101 rows = ['<tr><td bgcolor="#d8bbff">%s%s %s</td></tr>' %
102 ('<big>&nbsp;</big>', link, call)]
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000103 if index is not None:
104 i = lnum - index
105 for line in lines:
Ka-Ping Yee83205972001-08-21 06:53:01 +0000106 num = small('&nbsp;' * (5-len(str(i))) + str(i)) + '&nbsp;'
107 line = '<tt>%s%s</tt>' % (num, pydoc.html.preformat(line))
108 if i in highlight:
109 rows.append('<tr><td bgcolor="#ffccee">%s</td></tr>' % line)
110 else:
111 rows.append('<tr><td>%s</td></tr>' % grey(line))
112 i += 1
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000113
Ka-Ping Yee83205972001-08-21 06:53:01 +0000114 done, dump = {}, []
115 for name, where, value in vars:
116 if name in done: continue
117 done[name] = 1
118 if value is not __UNDEF__:
119 if where == 'global': name = '<em>global</em> ' + strong(name)
120 elif where == 'local': name = strong(name)
121 else: name = where + strong(name.split('.')[-1])
122 dump.append('%s&nbsp;= %s' % (name, pydoc.html.repr(value)))
123 else:
124 dump.append(name + ' <em>undefined</em>')
125
126 rows.append('<tr><td>%s</td></tr>' % small(grey(', '.join(dump))))
127 frames.append('''<p>
128<table width="100%%" cellspacing=0 cellpadding=0 border=0>
129%s</table>''' % '\n'.join(rows))
130
131 exception = ['<p>%s: %s' % (strong(str(etype)), str(evalue))]
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000132 if type(evalue) is types.InstanceType:
133 for name in dir(evalue):
134 value = pydoc.html.repr(getattr(evalue, name))
135 exception.append('\n<br>%s%s&nbsp;=\n%s' % (indent, name, value))
136
137 import traceback
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000138 return head + ''.join(frames) + ''.join(exception) + '''
139
140
Ka-Ping Yee83205972001-08-21 06:53:01 +0000141<!-- The above is a description of an error in a Python program, formatted
142 for a Web browser because the 'cgitb' module was enabled. In case you
143 are not reading this in a Web browser, here is the original traceback:
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000144
145%s
146-->
Ka-Ping Yee83205972001-08-21 06:53:01 +0000147''' % ''.join(traceback.format_exception(etype, evalue, etb))
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000148
149class Hook:
Ka-Ping Yee83205972001-08-21 06:53:01 +0000150 """A hook to replace sys.excepthook that shows tracebacks in HTML."""
151
152 def __init__(self, display=1, logdir=None, context=5):
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000153 self.display = display # send tracebacks to browser if true
154 self.logdir = logdir # log tracebacks to files if not None
Ka-Ping Yee83205972001-08-21 06:53:01 +0000155 self.context = context # number of source code lines per frame
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000156
157 def __call__(self, etype, evalue, etb):
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000158 self.handle((etype, evalue, etb))
159
160 def handle(self, info=None):
Ka-Ping Yee83205972001-08-21 06:53:01 +0000161 import sys
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000162 info = info or sys.exc_info()
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000163 print reset()
164
165 try:
Ka-Ping Yee83205972001-08-21 06:53:01 +0000166 text, doc = 0, html(info, self.context)
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000167 except: # just in case something goes wrong
168 import traceback
Ka-Ping Yee83205972001-08-21 06:53:01 +0000169 text, doc = 1, ''.join(traceback.format_exception(*info))
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000170
171 if self.display:
172 if text:
173 doc = doc.replace('&', '&amp;').replace('<', '&lt;')
Ka-Ping Yee83205972001-08-21 06:53:01 +0000174 print '<pre>' + doc + '</pre>'
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000175 else:
176 print doc
177 else:
178 print '<p>A problem occurred in a Python script.'
179
180 if self.logdir is not None:
Ka-Ping Yee83205972001-08-21 06:53:01 +0000181 import os, tempfile
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000182 name = tempfile.mktemp(['.html', '.txt'][text])
183 path = os.path.join(self.logdir, os.path.basename(name))
184 try:
185 file = open(path, 'w')
186 file.write(doc)
187 file.close()
Ka-Ping Yee83205972001-08-21 06:53:01 +0000188 print '<p> %s contains the description of this error.' % path
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000189 except:
Ka-Ping Yee83205972001-08-21 06:53:01 +0000190 print '<p> Tried to save traceback to %s, but failed.' % path
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000191
192handler = Hook().handle
Ka-Ping Yee83205972001-08-21 06:53:01 +0000193def enable(display=1, logdir=None, context=5):
194 """Install an exception handler that formats tracebacks as HTML.
195
196 The optional argument 'display' can be set to 0 to suppress sending the
197 traceback to the browser, and 'logdir' can be set to a directory to cause
198 tracebacks to be written to files there."""
Ka-Ping Yee6b5a48d2001-08-18 04:04:50 +0000199 import sys
Ka-Ping Yee83205972001-08-21 06:53:01 +0000200 sys.excepthook = Hook(display, logdir, context)