|
19365
|
1 """Handle exceptions in CGI scripts by formatting tracebacks into nice HTML.
|
|
|
2
|
|
|
3 To enable this module, do:
|
|
|
4
|
|
|
5 import cgitb; cgitb.enable()
|
|
|
6
|
|
|
7 at 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
|
|
19421
|
11 context - number of lines of source code to show for each stack frame
|
|
19365
|
12
|
|
19421
|
13 By default, tracebacks are displayed but not saved, and context is 5.
|
|
19365
|
14
|
|
|
15 Alternatively, if you have caught an exception and want cgitb to display it
|
|
|
16 for you, call cgitb.handle(). The optional argument to handle() is a 3-item
|
|
|
17 tuple (etype, evalue, etb) just like the value of sys.exc_info()."""
|
|
|
18
|
|
|
19 __author__ = 'Ka-Ping Yee'
|
|
|
20 __version__ = '$Revision$'
|
|
|
21
|
|
|
22 def reset():
|
|
|
23 """Return a string that resets the CGI and browser to a known state."""
|
|
|
24 return '''<!--: spam
|
|
|
25 Content-Type: text/html
|
|
|
26
|
|
19421
|
27 <body bgcolor="#f0f0f8"><font color="#f0f0f8" size="-5"> -->
|
|
|
28 <body bgcolor="#f0f0f8"><font color="#f0f0f8" size="-5"> --> -->
|
|
19365
|
29 </font> </font> </font> </script> </object> </blockquote> </pre>
|
|
|
30 </table> </table> </table> </table> </table> </font> </font> </font>'''
|
|
|
31
|
|
19421
|
32 __UNDEF__ = [] # a special sentinel object
|
|
|
33 def small(text): return '<small>' + text + '</small>'
|
|
|
34 def strong(text): return '<strong>' + text + '</strong>'
|
|
|
35 def grey(text): return '<font color="#909090">' + text + '</font>'
|
|
|
36
|
|
|
37 def 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
|
|
|
45 def 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
|
|
|
67 def 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
|
|
19365
|
70
|
|
|
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())
|
|
19421
|
75 head = '<body bgcolor="#f0f0f8">' + pydoc.html.heading(
|
|
19365
|
76 '<big><big><strong>%s</strong></big></big>' % str(etype),
|
|
19421
|
77 '#ffffff', '#6622aa', pyver + '<br>' + date) + '''
|
|
|
78 <p>A problem occurred in a Python script. Here is the sequence of
|
|
|
79 function calls leading up to the error, in the order they occurred.'''
|
|
19365
|
80
|
|
19421
|
81 indent = '<tt>' + small(' ' * 5) + ' </tt>'
|
|
19365
|
82 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 '?'
|
|
19421
|
86 link = '<a href="file://%s">%s</a>' % (file, pydoc.html.escape(file))
|
|
19365
|
87 args, varargs, varkw, locals = inspect.getargvalues(frame)
|
|
19421
|
88 call = ''
|
|
|
89 if func != '?':
|
|
|
90 call = 'in ' + strong(func) + \
|
|
|
91 inspect.formatargvalues(args, varargs, varkw, locals,
|
|
|
92 formatvalue=lambda value: '=' + pydoc.html.repr(value))
|
|
19365
|
93
|
|
19421
|
94 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)
|
|
19365
|
100
|
|
19421
|
101 rows = ['<tr><td bgcolor="#d8bbff">%s%s %s</td></tr>' %
|
|
|
102 ('<big> </big>', link, call)]
|
|
19365
|
103 if index is not None:
|
|
|
104 i = lnum - index
|
|
|
105 for line in lines:
|
|
19421
|
106 num = small(' ' * (5-len(str(i))) + str(i)) + ' '
|
|
|
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
|
|
19365
|
113
|
|
19421
|
114 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 = %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))]
|
|
19365
|
132 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 =\n%s' % (indent, name, value))
|
|
|
136
|
|
|
137 import traceback
|
|
|
138 return head + ''.join(frames) + ''.join(exception) + '''
|
|
|
139
|
|
|
140
|
|
19421
|
141 <!-- 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:
|
|
19365
|
144
|
|
|
145 %s
|
|
|
146 -->
|
|
19421
|
147 ''' % ''.join(traceback.format_exception(etype, evalue, etb))
|
|
19365
|
148
|
|
|
149 class Hook:
|
|
19421
|
150 """A hook to replace sys.excepthook that shows tracebacks in HTML."""
|
|
|
151
|
|
|
152 def __init__(self, display=1, logdir=None, context=5):
|
|
19365
|
153 self.display = display # send tracebacks to browser if true
|
|
|
154 self.logdir = logdir # log tracebacks to files if not None
|
|
19421
|
155 self.context = context # number of source code lines per frame
|
|
19365
|
156
|
|
|
157 def __call__(self, etype, evalue, etb):
|
|
|
158 self.handle((etype, evalue, etb))
|
|
|
159
|
|
|
160 def handle(self, info=None):
|
|
19421
|
161 import sys
|
|
19365
|
162 info = info or sys.exc_info()
|
|
|
163 print reset()
|
|
|
164
|
|
|
165 try:
|
|
19421
|
166 text, doc = 0, html(info, self.context)
|
|
19365
|
167 except: # just in case something goes wrong
|
|
|
168 import traceback
|
|
19421
|
169 text, doc = 1, ''.join(traceback.format_exception(*info))
|
|
19365
|
170
|
|
|
171 if self.display:
|
|
|
172 if text:
|
|
|
173 doc = doc.replace('&', '&').replace('<', '<')
|
|
19421
|
174 print '<pre>' + doc + '</pre>'
|
|
19365
|
175 else:
|
|
|
176 print doc
|
|
|
177 else:
|
|
|
178 print '<p>A problem occurred in a Python script.'
|
|
|
179
|
|
|
180 if self.logdir is not None:
|
|
19421
|
181 import os, tempfile
|
|
19365
|
182 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()
|
|
19421
|
188 print '<p> %s contains the description of this error.' % path
|
|
19365
|
189 except:
|
|
19421
|
190 print '<p> Tried to save traceback to %s, but failed.' % path
|
|
19365
|
191
|
|
|
192 handler = Hook().handle
|
|
19421
|
193 def 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."""
|
|
19365
|
199 import sys
|
|
19421
|
200 sys.excepthook = Hook(display, logdir, context)
|