1 """More comprehensive traceback formatting for Python scripts.
3 To enable this module, do:
5 import cgitb; cgitb.enable()
7 at the top of your script. The optional arguments to enable() are:
9 display - if true, tracebacks are displayed in the web browser
10 logdir - if set, tracebacks are written to files in this directory
11 context - number of lines of source code to show for each stack frame
12 format - 'text' or 'html' controls the output format
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)
18 Alternatively, if you have caught an exception and want cgitb to display it
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.
24 __author__
= 'Ka-Ping Yee'
25 __version__
= '$Revision$'
30 """Return a string that resets the CGI and browser to a known state."""
32 Content-Type: text/html
34 <body bgcolor="#f0f0f8"><font color="#f0f0f8" size="-5"> -->
35 <body bgcolor="#f0f0f8"><font color="#f0f0f8" size="-5"> --> -->
36 </font> </font> </font> </script> </object> </blockquote> </pre>
37 </table> </table> </table> </table> </table> </font> </font> </font>'''
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>'
44 def lookup(name
, frame
, locals):
45 """Find the value for a given name in the given environment."""
47 return 'local', locals[name
]
48 if name
in frame
.f_globals
:
49 return 'global', frame
.f_globals
[name
]
50 if '__builtins__' in frame
.f_globals
:
51 builtins
= frame
.f_globals
['__builtins__']
52 if type(builtins
) is type({}):
54 return 'builtin', builtins
[name
]
56 if hasattr(builtins
, name
):
57 return 'builtin', getattr(builtins
, name
)
58 return None, __UNDEF__
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
:
68 if parent
is not __UNDEF__
:
69 value
= getattr(parent
, token
, __UNDEF__
)
70 vars.append((prefix
+ token
, prefix
, value
))
72 where
, value
= lookup(token
, frame
, locals)
73 vars.append((token
, where
, value
))
75 prefix
+= lasttoken
+ '.'
78 parent
, prefix
= None, ''
82 def html((etype
, evalue
, etb
), context
=5):
83 """Return a nice HTML document describing a given traceback."""
84 import os
, types
, time
, traceback
, linecache
, inspect
, pydoc
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())
90 head
= '<body bgcolor="#f0f0f8">' + pydoc
.html
.heading(
91 '<big><big><strong>%s</strong></big></big>' % str(etype
),
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.'''
96 indent
= '<tt>' + small(' ' * 5) + ' </tt>'
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 '?'
101 link
= '<a href="file://%s">%s</a>' % (file, pydoc
.html
.escape(file))
102 args
, varargs
, varkw
, locals = inspect
.getargvalues(frame
)
105 call
= 'in ' + strong(func
) + \
106 inspect
.formatargvalues(args
, varargs
, varkw
, locals,
107 formatvalue
=lambda value
: '=' + pydoc
.html
.repr(value
))
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)
116 rows
= ['<tr><td bgcolor="#d8bbff">%s%s %s</td></tr>' %
117 ('<big> </big>', link
, call
)]
118 if index
is not None:
121 num
= small(' ' * (5-len(str(i
))) + str(i
)) + ' '
122 line
= '<tt>%s%s</tt>' % (num
, pydoc
.html
.preformat(line
))
124 rows
.append('<tr><td bgcolor="#ffccee">%s</td></tr>' % line
)
126 rows
.append('<tr><td>%s</td></tr>' % grey(line
))
130 for name
, where
, value
in vars:
131 if name
in done
: continue
133 if value
is not __UNDEF__
:
134 if where
in ['global', 'builtin']:
135 name
= ('<em>%s</em> ' % where
) + strong(name
)
136 elif where
== 'local':
139 name
= where
+ strong(name
.split('.')[-1])
140 dump
.append('%s = %s' % (name
, pydoc
.html
.repr(value
)))
142 dump
.append(name
+ ' <em>undefined</em>')
144 rows
.append('<tr><td>%s</td></tr>' % small(grey(', '.join(dump
))))
146 <table width="100%%" cellspacing=0 cellpadding=0 border=0>
147 %s</table>''' % '\n'.join(rows
))
149 exception
= ['<p>%s: %s' % (strong(str(etype
)), str(evalue
))]
150 if type(evalue
) is types
.InstanceType
:
151 for name
in dir(evalue
):
152 if name
[:1] == '_': continue
153 value
= pydoc
.html
.repr(getattr(evalue
, name
))
154 exception
.append('\n<br>%s%s =\n%s' % (indent
, name
, value
))
157 return head
+ ''.join(frames
) + ''.join(exception
) + '''
160 <!-- The above is a description of an error in a Python program, formatted
161 for a Web browser because the 'cgitb' module was enabled. In case you
162 are not reading this in a Web browser, here is the original traceback:
166 ''' % ''.join(traceback
.format_exception(etype
, evalue
, etb
))
168 def text((etype
, evalue
, etb
), context
=5):
169 """Return a plain text document describing a given traceback."""
170 import os
, types
, time
, traceback
, linecache
, inspect
, pydoc
172 if type(etype
) is types
.ClassType
:
173 etype
= etype
.__name
__
174 pyver
= 'Python ' + sys
.version
.split()[0] + ': ' + sys
.executable
175 date
= time
.ctime(time
.time())
176 head
= "%s\n%s\n%s\n" % (str(etype
), pyver
, date
) + '''
177 A problem occurred in a Python script. Here is the sequence of
178 function calls leading up to the error, in the order they occurred.
182 records
= inspect
.getinnerframes(etb
, context
)
183 for frame
, file, lnum
, func
, lines
, index
in records
:
184 file = file and os
.path
.abspath(file) or '?'
185 args
, varargs
, varkw
, locals = inspect
.getargvalues(frame
)
188 call
= 'in ' + func
+ \
189 inspect
.formatargvalues(args
, varargs
, varkw
, locals,
190 formatvalue
=lambda value
: '=' + pydoc
.text
.repr(value
))
193 def reader(lnum
=[lnum
]):
194 highlight
[lnum
[0]] = 1
195 try: return linecache
.getline(file, lnum
[0])
196 finally: lnum
[0] += 1
197 vars = scanvars(reader
, frame
, locals)
199 rows
= [' %s %s' % (file, call
)]
200 if index
is not None:
204 rows
.append(num
+line
.rstrip())
208 for name
, where
, value
in vars:
209 if name
in done
: continue
211 if value
is not __UNDEF__
:
212 if where
== 'global': name
= 'global ' + name
213 elif where
== 'local': name
= name
214 else: name
= where
+ name
.split('.')[-1]
215 dump
.append('%s = %s' % (name
, pydoc
.text
.repr(value
)))
217 dump
.append(name
+ ' undefined')
219 rows
.append('\n'.join(dump
))
220 frames
.append('\n%s\n' % '\n'.join(rows
))
222 exception
= ['%s: %s' % (str(etype
), str(evalue
))]
223 if type(evalue
) is types
.InstanceType
:
224 for name
in dir(evalue
):
225 value
= pydoc
.text
.repr(getattr(evalue
, name
))
226 exception
.append('\n%s%s = %s' % (" "*4, name
, value
))
229 return head
+ ''.join(frames
) + ''.join(exception
) + '''
231 The above is a description of an error in a Python program. Here is
232 the original traceback:
235 ''' % ''.join(traceback
.format_exception(etype
, evalue
, etb
))
238 """A hook to replace sys.excepthook that shows tracebacks in HTML."""
240 def __init__(self
, display
=1, logdir
=None, context
=5, file=None,
242 self
.display
= display
# send tracebacks to browser if true
243 self
.logdir
= logdir
# log tracebacks to files if not None
244 self
.context
= context
# number of source code lines per frame
245 self
.file = file or sys
.stdout
# place to send the output
248 def __call__(self
, etype
, evalue
, etb
):
249 self
.handle((etype
, evalue
, etb
))
251 def handle(self
, info
=None):
252 info
= info
or sys
.exc_info()
253 if self
.format
== "html":
254 self
.file.write(reset())
256 formatter
= (self
.format
=="html") and html
or text
259 doc
= formatter(info
, self
.context
)
260 except: # just in case something goes wrong
262 doc
= ''.join(traceback
.format_exception(*info
))
267 doc
= doc
.replace('&', '&').replace('<', '<')
268 self
.file.write('<pre>' + doc
+ '</pre>\n')
270 self
.file.write(doc
+ '\n')
272 self
.file.write('<p>A problem occurred in a Python script.\n')
274 if self
.logdir
is not None:
276 suffix
= ['.html', '.txt'][self
.format
=="html"]
277 (fd
, path
) = tempfile
.mkstemp(suffix
=suffix
, dir=self
.logdir
)
279 file = os
.fdopen(fd
, 'w')
282 msg
= '<p> %s contains the description of this error.' % path
284 msg
= '<p> Tried to save traceback to %s, but failed.' % path
285 self
.file.write(msg
+ '\n')
290 handler
= Hook().handle
291 def enable(display
=1, logdir
=None, context
=5, format
="html"):
292 """Install an exception handler that formats tracebacks as HTML.
294 The optional argument 'display' can be set to 0 to suppress sending the
295 traceback to the browser, and 'logdir' can be set to a directory to cause
296 tracebacks to be written to files there."""
297 sys
.excepthook
= Hook(display
=display
, logdir
=logdir
,
298 context
=context
, format
=format
)