2003-06-17 09:58:31 -03:00
|
|
|
"""More comprehensive traceback formatting for Python scripts.
|
2001-08-18 01:04:50 -03:00
|
|
|
|
|
|
|
To enable this module, do:
|
|
|
|
|
|
|
|
import cgitb; cgitb.enable()
|
|
|
|
|
2003-06-17 09:58:31 -03:00
|
|
|
at the top of your script. The optional arguments to enable() are:
|
2001-08-18 01:04:50 -03:00
|
|
|
|
|
|
|
display - if true, tracebacks are displayed in the web browser
|
|
|
|
logdir - if set, tracebacks are written to files in this directory
|
2001-08-21 03:53:01 -03:00
|
|
|
context - number of lines of source code to show for each stack frame
|
2003-06-29 02:46:54 -03:00
|
|
|
format - 'text' or 'html' controls the output format
|
2001-08-18 01:04:50 -03:00
|
|
|
|
2003-06-17 09:58:31 -03:00
|
|
|
By default, tracebacks are displayed but not saved, the context is 5 lines
|
|
|
|
and the output format is 'html' (for backwards compatibility with the
|
|
|
|
original use of this module)
|
2001-08-18 01:04:50 -03:00
|
|
|
|
|
|
|
Alternatively, if you have caught an exception and want cgitb to display it
|
2003-06-17 09:58:31 -03:00
|
|
|
for you, call cgitb.handler(). The optional argument to handler() is a
|
|
|
|
3-item tuple (etype, evalue, etb) just like the value of sys.exc_info().
|
|
|
|
The default handler displays output as HTML.
|
2001-08-18 01:04:50 -03:00
|
|
|
|
2009-04-01 13:00:34 -03:00
|
|
|
"""
|
|
|
|
import inspect
|
|
|
|
import keyword
|
|
|
|
import linecache
|
|
|
|
import os
|
|
|
|
import pydoc
|
2001-12-04 14:45:17 -04:00
|
|
|
import sys
|
2009-04-01 13:00:34 -03:00
|
|
|
import tempfile
|
|
|
|
import time
|
|
|
|
import tokenize
|
|
|
|
import traceback
|
|
|
|
import types
|
2001-12-04 14:45:17 -04:00
|
|
|
|
2001-08-18 01:04:50 -03:00
|
|
|
def reset():
|
|
|
|
"""Return a string that resets the CGI and browser to a known state."""
|
|
|
|
return '''<!--: spam
|
|
|
|
Content-Type: text/html
|
|
|
|
|
2001-08-21 03:53:01 -03:00
|
|
|
<body bgcolor="#f0f0f8"><font color="#f0f0f8" size="-5"> -->
|
|
|
|
<body bgcolor="#f0f0f8"><font color="#f0f0f8" size="-5"> --> -->
|
2001-08-18 01:04:50 -03:00
|
|
|
</font> </font> </font> </script> </object> </blockquote> </pre>
|
|
|
|
</table> </table> </table> </table> </table> </font> </font> </font>'''
|
|
|
|
|
2001-08-21 03:53:01 -03:00
|
|
|
__UNDEF__ = [] # a special sentinel object
|
2004-07-10 11:14:51 -03:00
|
|
|
def small(text):
|
|
|
|
if text:
|
|
|
|
return '<small>' + text + '</small>'
|
|
|
|
else:
|
|
|
|
return ''
|
2004-07-18 03:16:08 -03:00
|
|
|
|
2004-07-10 11:14:51 -03:00
|
|
|
def strong(text):
|
|
|
|
if text:
|
|
|
|
return '<strong>' + text + '</strong>'
|
|
|
|
else:
|
|
|
|
return ''
|
2004-07-18 03:16:08 -03:00
|
|
|
|
2004-07-10 11:14:51 -03:00
|
|
|
def grey(text):
|
|
|
|
if text:
|
|
|
|
return '<font color="#909090">' + text + '</font>'
|
|
|
|
else:
|
|
|
|
return ''
|
2001-08-21 03:53:01 -03:00
|
|
|
|
|
|
|
def lookup(name, frame, locals):
|
|
|
|
"""Find the value for a given name in the given environment."""
|
|
|
|
if name in locals:
|
|
|
|
return 'local', locals[name]
|
|
|
|
if name in frame.f_globals:
|
|
|
|
return 'global', frame.f_globals[name]
|
2002-06-26 04:10:56 -03:00
|
|
|
if '__builtins__' in frame.f_globals:
|
|
|
|
builtins = frame.f_globals['__builtins__']
|
|
|
|
if type(builtins) is type({}):
|
|
|
|
if name in builtins:
|
|
|
|
return 'builtin', builtins[name]
|
|
|
|
else:
|
|
|
|
if hasattr(builtins, name):
|
|
|
|
return 'builtin', getattr(builtins, name)
|
2001-08-21 03:53:01 -03:00
|
|
|
return None, __UNDEF__
|
|
|
|
|
|
|
|
def scanvars(reader, frame, locals):
|
|
|
|
"""Scan one logical line of Python and look up values of variables used."""
|
2004-06-05 16:15:34 -03:00
|
|
|
vars, lasttoken, parent, prefix, value = [], None, None, '', __UNDEF__
|
2001-08-21 03:53:01 -03:00
|
|
|
for ttype, token, start, end, line in tokenize.generate_tokens(reader):
|
|
|
|
if ttype == tokenize.NEWLINE: break
|
|
|
|
if ttype == tokenize.NAME and token not in keyword.kwlist:
|
|
|
|
if lasttoken == '.':
|
|
|
|
if parent is not __UNDEF__:
|
|
|
|
value = getattr(parent, token, __UNDEF__)
|
|
|
|
vars.append((prefix + token, prefix, value))
|
|
|
|
else:
|
|
|
|
where, value = lookup(token, frame, locals)
|
|
|
|
vars.append((token, where, value))
|
|
|
|
elif token == '.':
|
|
|
|
prefix += lasttoken + '.'
|
|
|
|
parent = value
|
|
|
|
else:
|
|
|
|
parent, prefix = None, ''
|
|
|
|
lasttoken = token
|
|
|
|
return vars
|
|
|
|
|
|
|
|
def html((etype, evalue, etb), context=5):
|
|
|
|
"""Return a nice HTML document describing a given traceback."""
|
2001-08-18 01:04:50 -03:00
|
|
|
if type(etype) is types.ClassType:
|
|
|
|
etype = etype.__name__
|
|
|
|
pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
|
|
|
|
date = time.ctime(time.time())
|
2001-08-21 03:53:01 -03:00
|
|
|
head = '<body bgcolor="#f0f0f8">' + pydoc.html.heading(
|
2004-07-10 11:14:51 -03:00
|
|
|
'<big><big>%s</big></big>' %
|
|
|
|
strong(pydoc.html.escape(str(etype))),
|
2001-08-21 03:53:01 -03:00
|
|
|
'#ffffff', '#6622aa', pyver + '<br>' + date) + '''
|
|
|
|
<p>A problem occurred in a Python script. Here is the sequence of
|
2004-07-10 11:14:51 -03:00
|
|
|
function calls leading up to the error, in the order they occurred.</p>'''
|
2001-08-18 01:04:50 -03:00
|
|
|
|
2001-08-21 03:53:01 -03:00
|
|
|
indent = '<tt>' + small(' ' * 5) + ' </tt>'
|
2001-08-18 01:04:50 -03:00
|
|
|
frames = []
|
|
|
|
records = inspect.getinnerframes(etb, context)
|
|
|
|
for frame, file, lnum, func, lines, index in records:
|
2005-06-26 18:57:55 -03:00
|
|
|
if file:
|
|
|
|
file = os.path.abspath(file)
|
|
|
|
link = '<a href="file://%s">%s</a>' % (file, pydoc.html.escape(file))
|
|
|
|
else:
|
|
|
|
file = link = '?'
|
2001-08-18 01:04:50 -03:00
|
|
|
args, varargs, varkw, locals = inspect.getargvalues(frame)
|
2001-08-21 03:53:01 -03:00
|
|
|
call = ''
|
|
|
|
if func != '?':
|
|
|
|
call = 'in ' + strong(func) + \
|
|
|
|
inspect.formatargvalues(args, varargs, varkw, locals,
|
|
|
|
formatvalue=lambda value: '=' + pydoc.html.repr(value))
|
|
|
|
|
|
|
|
highlight = {}
|
|
|
|
def reader(lnum=[lnum]):
|
|
|
|
highlight[lnum[0]] = 1
|
|
|
|
try: return linecache.getline(file, lnum[0])
|
|
|
|
finally: lnum[0] += 1
|
|
|
|
vars = scanvars(reader, frame, locals)
|
|
|
|
|
|
|
|
rows = ['<tr><td bgcolor="#d8bbff">%s%s %s</td></tr>' %
|
|
|
|
('<big> </big>', link, call)]
|
2001-08-18 01:04:50 -03:00
|
|
|
if index is not None:
|
|
|
|
i = lnum - index
|
|
|
|
for line in lines:
|
2001-08-21 03:53:01 -03:00
|
|
|
num = small(' ' * (5-len(str(i))) + str(i)) + ' '
|
|
|
|
line = '<tt>%s%s</tt>' % (num, pydoc.html.preformat(line))
|
|
|
|
if i in highlight:
|
|
|
|
rows.append('<tr><td bgcolor="#ffccee">%s</td></tr>' % line)
|
|
|
|
else:
|
|
|
|
rows.append('<tr><td>%s</td></tr>' % grey(line))
|
|
|
|
i += 1
|
|
|
|
|
|
|
|
done, dump = {}, []
|
|
|
|
for name, where, value in vars:
|
|
|
|
if name in done: continue
|
|
|
|
done[name] = 1
|
|
|
|
if value is not __UNDEF__:
|
2005-02-06 02:57:08 -04:00
|
|
|
if where in ('global', 'builtin'):
|
2002-06-26 04:10:56 -03:00
|
|
|
name = ('<em>%s</em> ' % where) + strong(name)
|
|
|
|
elif where == 'local':
|
|
|
|
name = strong(name)
|
|
|
|
else:
|
|
|
|
name = where + strong(name.split('.')[-1])
|
2001-08-21 03:53:01 -03:00
|
|
|
dump.append('%s = %s' % (name, pydoc.html.repr(value)))
|
|
|
|
else:
|
|
|
|
dump.append(name + ' <em>undefined</em>')
|
|
|
|
|
|
|
|
rows.append('<tr><td>%s</td></tr>' % small(grey(', '.join(dump))))
|
2004-07-10 11:14:51 -03:00
|
|
|
frames.append('''
|
2001-08-21 03:53:01 -03:00
|
|
|
<table width="100%%" cellspacing=0 cellpadding=0 border=0>
|
|
|
|
%s</table>''' % '\n'.join(rows))
|
|
|
|
|
2004-03-31 16:17:56 -04:00
|
|
|
exception = ['<p>%s: %s' % (strong(pydoc.html.escape(str(etype))),
|
|
|
|
pydoc.html.escape(str(evalue)))]
|
2007-04-11 16:25:11 -03:00
|
|
|
if isinstance(evalue, BaseException):
|
2001-08-18 01:04:50 -03:00
|
|
|
for name in dir(evalue):
|
2002-06-26 04:10:56 -03:00
|
|
|
if name[:1] == '_': continue
|
2001-08-18 01:04:50 -03:00
|
|
|
value = pydoc.html.repr(getattr(evalue, name))
|
|
|
|
exception.append('\n<br>%s%s =\n%s' % (indent, name, value))
|
|
|
|
|
|
|
|
return head + ''.join(frames) + ''.join(exception) + '''
|
|
|
|
|
|
|
|
|
2001-08-21 03:53:01 -03:00
|
|
|
<!-- The above is a description of an error in a Python program, formatted
|
|
|
|
for a Web browser because the 'cgitb' module was enabled. In case you
|
|
|
|
are not reading this in a Web browser, here is the original traceback:
|
2001-08-18 01:04:50 -03:00
|
|
|
|
|
|
|
%s
|
|
|
|
-->
|
2007-05-15 17:19:34 -03:00
|
|
|
''' % pydoc.html.escape(
|
|
|
|
''.join(traceback.format_exception(etype, evalue, etb)))
|
2001-08-18 01:04:50 -03:00
|
|
|
|
2003-06-17 09:58:31 -03:00
|
|
|
def text((etype, evalue, etb), context=5):
|
|
|
|
"""Return a plain text document describing a given traceback."""
|
|
|
|
if type(etype) is types.ClassType:
|
|
|
|
etype = etype.__name__
|
|
|
|
pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
|
|
|
|
date = time.ctime(time.time())
|
|
|
|
head = "%s\n%s\n%s\n" % (str(etype), pyver, date) + '''
|
|
|
|
A problem occurred in a Python script. Here is the sequence of
|
|
|
|
function calls leading up to the error, in the order they occurred.
|
|
|
|
'''
|
|
|
|
|
|
|
|
frames = []
|
|
|
|
records = inspect.getinnerframes(etb, context)
|
|
|
|
for frame, file, lnum, func, lines, index in records:
|
|
|
|
file = file and os.path.abspath(file) or '?'
|
|
|
|
args, varargs, varkw, locals = inspect.getargvalues(frame)
|
|
|
|
call = ''
|
|
|
|
if func != '?':
|
|
|
|
call = 'in ' + func + \
|
|
|
|
inspect.formatargvalues(args, varargs, varkw, locals,
|
|
|
|
formatvalue=lambda value: '=' + pydoc.text.repr(value))
|
|
|
|
|
|
|
|
highlight = {}
|
|
|
|
def reader(lnum=[lnum]):
|
|
|
|
highlight[lnum[0]] = 1
|
|
|
|
try: return linecache.getline(file, lnum[0])
|
|
|
|
finally: lnum[0] += 1
|
|
|
|
vars = scanvars(reader, frame, locals)
|
|
|
|
|
|
|
|
rows = [' %s %s' % (file, call)]
|
|
|
|
if index is not None:
|
|
|
|
i = lnum - index
|
|
|
|
for line in lines:
|
|
|
|
num = '%5d ' % i
|
|
|
|
rows.append(num+line.rstrip())
|
|
|
|
i += 1
|
|
|
|
|
|
|
|
done, dump = {}, []
|
|
|
|
for name, where, value in vars:
|
|
|
|
if name in done: continue
|
|
|
|
done[name] = 1
|
|
|
|
if value is not __UNDEF__:
|
|
|
|
if where == 'global': name = 'global ' + name
|
2004-06-07 08:20:40 -03:00
|
|
|
elif where != 'local': name = where + name.split('.')[-1]
|
2003-06-17 09:58:31 -03:00
|
|
|
dump.append('%s = %s' % (name, pydoc.text.repr(value)))
|
|
|
|
else:
|
|
|
|
dump.append(name + ' undefined')
|
|
|
|
|
|
|
|
rows.append('\n'.join(dump))
|
|
|
|
frames.append('\n%s\n' % '\n'.join(rows))
|
|
|
|
|
|
|
|
exception = ['%s: %s' % (str(etype), str(evalue))]
|
2007-04-11 16:25:11 -03:00
|
|
|
if isinstance(evalue, BaseException):
|
2003-06-17 09:58:31 -03:00
|
|
|
for name in dir(evalue):
|
|
|
|
value = pydoc.text.repr(getattr(evalue, name))
|
|
|
|
exception.append('\n%s%s = %s' % (" "*4, name, value))
|
|
|
|
|
|
|
|
return head + ''.join(frames) + ''.join(exception) + '''
|
|
|
|
|
|
|
|
The above is a description of an error in a Python program. Here is
|
|
|
|
the original traceback:
|
|
|
|
|
|
|
|
%s
|
|
|
|
''' % ''.join(traceback.format_exception(etype, evalue, etb))
|
|
|
|
|
2001-08-18 01:04:50 -03:00
|
|
|
class Hook:
|
2001-08-21 03:53:01 -03:00
|
|
|
"""A hook to replace sys.excepthook that shows tracebacks in HTML."""
|
|
|
|
|
2003-06-17 09:58:31 -03:00
|
|
|
def __init__(self, display=1, logdir=None, context=5, file=None,
|
|
|
|
format="html"):
|
2001-08-18 01:04:50 -03:00
|
|
|
self.display = display # send tracebacks to browser if true
|
|
|
|
self.logdir = logdir # log tracebacks to files if not None
|
2001-08-21 03:53:01 -03:00
|
|
|
self.context = context # number of source code lines per frame
|
2001-12-04 14:45:17 -04:00
|
|
|
self.file = file or sys.stdout # place to send the output
|
2003-06-17 09:58:31 -03:00
|
|
|
self.format = format
|
2001-08-18 01:04:50 -03:00
|
|
|
|
|
|
|
def __call__(self, etype, evalue, etb):
|
|
|
|
self.handle((etype, evalue, etb))
|
|
|
|
|
|
|
|
def handle(self, info=None):
|
|
|
|
info = info or sys.exc_info()
|
2003-06-17 09:58:31 -03:00
|
|
|
if self.format == "html":
|
|
|
|
self.file.write(reset())
|
2001-08-18 01:04:50 -03:00
|
|
|
|
2003-06-17 09:58:31 -03:00
|
|
|
formatter = (self.format=="html") and html or text
|
|
|
|
plain = False
|
2001-08-18 01:04:50 -03:00
|
|
|
try:
|
2003-06-17 09:58:31 -03:00
|
|
|
doc = formatter(info, self.context)
|
2001-08-18 01:04:50 -03:00
|
|
|
except: # just in case something goes wrong
|
2003-06-17 09:58:31 -03:00
|
|
|
doc = ''.join(traceback.format_exception(*info))
|
|
|
|
plain = True
|
2001-08-18 01:04:50 -03:00
|
|
|
|
|
|
|
if self.display:
|
2003-06-17 09:58:31 -03:00
|
|
|
if plain:
|
2001-08-18 01:04:50 -03:00
|
|
|
doc = doc.replace('&', '&').replace('<', '<')
|
2001-12-04 14:45:17 -04:00
|
|
|
self.file.write('<pre>' + doc + '</pre>\n')
|
2001-08-18 01:04:50 -03:00
|
|
|
else:
|
2001-12-04 14:45:17 -04:00
|
|
|
self.file.write(doc + '\n')
|
2001-08-18 01:04:50 -03:00
|
|
|
else:
|
2001-12-04 14:45:17 -04:00
|
|
|
self.file.write('<p>A problem occurred in a Python script.\n')
|
2001-08-18 01:04:50 -03:00
|
|
|
|
|
|
|
if self.logdir is not None:
|
2004-05-06 10:13:44 -03:00
|
|
|
suffix = ['.txt', '.html'][self.format=="html"]
|
2003-06-17 09:58:31 -03:00
|
|
|
(fd, path) = tempfile.mkstemp(suffix=suffix, dir=self.logdir)
|
2001-08-18 01:04:50 -03:00
|
|
|
try:
|
2002-08-09 13:38:32 -03:00
|
|
|
file = os.fdopen(fd, 'w')
|
2001-08-18 01:04:50 -03:00
|
|
|
file.write(doc)
|
|
|
|
file.close()
|
2001-12-04 14:45:17 -04:00
|
|
|
msg = '<p> %s contains the description of this error.' % path
|
2001-08-18 01:04:50 -03:00
|
|
|
except:
|
2001-12-04 14:45:17 -04:00
|
|
|
msg = '<p> Tried to save traceback to %s, but failed.' % path
|
|
|
|
self.file.write(msg + '\n')
|
|
|
|
try:
|
|
|
|
self.file.flush()
|
|
|
|
except: pass
|
2001-08-18 01:04:50 -03:00
|
|
|
|
|
|
|
handler = Hook().handle
|
2003-06-17 09:58:31 -03:00
|
|
|
def enable(display=1, logdir=None, context=5, format="html"):
|
2001-08-21 03:53:01 -03:00
|
|
|
"""Install an exception handler that formats tracebacks as HTML.
|
|
|
|
|
|
|
|
The optional argument 'display' can be set to 0 to suppress sending the
|
|
|
|
traceback to the browser, and 'logdir' can be set to a directory to cause
|
|
|
|
tracebacks to be written to files there."""
|
2003-06-17 09:58:31 -03:00
|
|
|
sys.excepthook = Hook(display=display, logdir=logdir,
|
|
|
|
context=context, format=format)
|