Kaydet (Commit) 83205972 authored tarafından Ka-Ping Yee's avatar Ka-Ping Yee

Enhancements:

- file URL now starts with "file://" (standard) rather than "file:"
- new optional argument 'context' to enable()
- repeated variable names don't have their values shown twice
- dotted attributes are shown; missing attributes handled reasonably
- highlight the whole logical line even if it has multiple physical lines
- use nice generator interface to tokenize
- formatting fixed so that it looks good in lynx, links, and w3m too
üst e81f4478
...@@ -8,8 +8,9 @@ at the top of your CGI script. The optional arguments to enable() are: ...@@ -8,8 +8,9 @@ at the top of your CGI script. The optional arguments to enable() are:
display - if true, tracebacks are displayed in the web browser display - if true, tracebacks are displayed in the web browser
logdir - if set, tracebacks are written to files in this directory logdir - if set, tracebacks are written to files in this directory
context - number of lines of source code to show for each stack frame
By default, tracebacks are displayed but not written to files. By default, tracebacks are displayed but not saved, and context is 5.
Alternatively, if you have caught an exception and want cgitb to display it Alternatively, if you have caught an exception and want cgitb to display it
for you, call cgitb.handle(). The optional argument to handle() is a 3-item for you, call cgitb.handle(). The optional argument to handle() is a 3-item
...@@ -23,160 +24,177 @@ def reset(): ...@@ -23,160 +24,177 @@ def reset():
return '''<!--: spam return '''<!--: spam
Content-Type: text/html Content-Type: text/html
<body bgcolor="#f0f0ff"><font color="#f0f0ff" size="-5"> --> <body bgcolor="#f0f0f8"><font color="#f0f0f8" size="-5"> -->
<body bgcolor="#f0f0ff"><font color="#f0f0ff" size="-5"> --> --> <body bgcolor="#f0f0f8"><font color="#f0f0f8" size="-5"> --> -->
</font> </font> </font> </script> </object> </blockquote> </pre> </font> </font> </font> </script> </object> </blockquote> </pre>
</table> </table> </table> </table> </table> </font> </font> </font>''' </table> </table> </table> </table> </table> </font> </font> </font>'''
def html(etype, evalue, etb, context=5): __UNDEF__ = [] # a special sentinel object
"""Return a nice HTML document describing the traceback.""" def small(text): return '<small>' + text + '</small>'
import sys, os, types, time, traceback def strong(text): return '<strong>' + text + '</strong>'
import keyword, tokenize, linecache, inspect, pydoc def grey(text): return '<font color="#909090">' + text + '</font>'
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]
return None, __UNDEF__
def scanvars(reader, frame, locals):
"""Scan one logical line of Python and look up values of variables used."""
import tokenize, keyword
vars, lasttoken, parent, prefix = [], None, None, ''
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."""
import sys, os, types, time, traceback, linecache, inspect, pydoc
if type(etype) is types.ClassType: if type(etype) is types.ClassType:
etype = etype.__name__ etype = etype.__name__
pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
date = time.ctime(time.time()) date = time.ctime(time.time())
head = '<body bgcolor="#f0f0ff">' + pydoc.html.heading( head = '<body bgcolor="#f0f0f8">' + pydoc.html.heading(
'<big><big><strong>%s</strong></big></big>' % str(etype), '<big><big><strong>%s</strong></big></big>' % str(etype),
'#ffffff', '#aa55cc', pyver + '<br>' + date) + ''' '#ffffff', '#6622aa', pyver + '<br>' + date) + '''
<p>A problem occurred in a Python script. <p>A problem occurred in a Python script. Here is the sequence of
Here is the sequence of function calls leading up to function calls leading up to the error, in the order they occurred.'''
the error, with the most recent (innermost) call last.'''
indent = '<tt><small>' + '&nbsp;' * 5 + '</small>&nbsp;</tt>' indent = '<tt>' + small('&nbsp;' * 5) + '&nbsp;</tt>'
frames = [] frames = []
records = inspect.getinnerframes(etb, context) records = inspect.getinnerframes(etb, context)
for frame, file, lnum, func, lines, index in records: for frame, file, lnum, func, lines, index in records:
file = file and os.path.abspath(file) or '?' file = file and os.path.abspath(file) or '?'
link = '<a href="file:%s">%s</a>' % (file, pydoc.html.escape(file)) link = '<a href="file://%s">%s</a>' % (file, pydoc.html.escape(file))
args, varargs, varkw, locals = inspect.getargvalues(frame) args, varargs, varkw, locals = inspect.getargvalues(frame)
if func == '?': call = ''
call = '' if func != '?':
else: call = 'in ' + strong(func) + \
def eqrepr(value): return '=' + pydoc.html.repr(value) inspect.formatargvalues(args, varargs, varkw, locals,
call = 'in <strong>%s</strong>' % func + inspect.formatargvalues( formatvalue=lambda value: '=' + pydoc.html.repr(value))
args, varargs, varkw, locals, formatvalue=eqrepr)
highlight = {}
names = [] def reader(lnum=[lnum]):
def tokeneater(type, token, start, end, line): highlight[lnum[0]] = 1
if type == tokenize.NAME and token not in keyword.kwlist: try: return linecache.getline(file, lnum[0])
if token not in names: names.append(token) finally: lnum[0] += 1
if type == tokenize.NEWLINE: raise IndexError vars = scanvars(reader, frame, locals)
def linereader(lnum=[lnum]):
line = linecache.getline(file, lnum[0]) rows = ['<tr><td bgcolor="#d8bbff">%s%s %s</td></tr>' %
lnum[0] += 1 ('<big>&nbsp;</big>', link, call)]
return line
try:
tokenize.tokenize(linereader, tokeneater)
except IndexError: pass
lvals = []
for name in names:
if name in frame.f_code.co_varnames:
if locals.has_key(name):
value = pydoc.html.repr(locals[name])
else:
value = '<em>undefined</em>'
name = '<strong>%s</strong>' % name
else:
if frame.f_globals.has_key(name):
value = pydoc.html.repr(frame.f_globals[name])
else:
value = '<em>undefined</em>'
name = '<em>global</em> <strong>%s</strong>' % name
lvals.append('%s&nbsp;= %s' % (name, value))
if lvals:
lvals = indent + '''
<small><font color="#909090">%s</font></small><br>''' % (', '.join(lvals))
else:
lvals = ''
level = '''
<table width="100%%" bgcolor="#d8bbff" cellspacing=0 cellpadding=2 border=0>
<tr><td>%s %s</td></tr></table>\n''' % (link, call)
excerpt = []
if index is not None: if index is not None:
i = lnum - index i = lnum - index
for line in lines: for line in lines:
num = '<small><font color="#909090">%s</font></small>' % ( num = small('&nbsp;' * (5-len(str(i))) + str(i)) + '&nbsp;'
'&nbsp;' * (5-len(str(i))) + str(i)) line = '<tt>%s%s</tt>' % (num, pydoc.html.preformat(line))
line = '<tt>%s&nbsp;%s</tt>' % (num, pydoc.html.preformat(line)) if i in highlight:
if i == lnum: rows.append('<tr><td bgcolor="#ffccee">%s</td></tr>' % line)
line = ''' else:
<table width="100%%" bgcolor="#ffccee" cellspacing=0 cellpadding=0 border=0> rows.append('<tr><td>%s</td></tr>' % grey(line))
<tr><td>%s</td></tr></table>\n''' % line i += 1
excerpt.append('\n' + line)
if i == lnum: done, dump = {}, []
excerpt.append(lvals) for name, where, value in vars:
i = i + 1 if name in done: continue
frames.append('<p>' + level + '\n'.join(excerpt)) done[name] = 1
if value is not __UNDEF__:
exception = ['<p><strong>%s</strong>: %s' % (str(etype), str(evalue))] if where == 'global': name = '<em>global</em> ' + strong(name)
elif where == 'local': name = strong(name)
else: name = where + strong(name.split('.')[-1])
dump.append('%s&nbsp;= %s' % (name, pydoc.html.repr(value)))
else:
dump.append(name + ' <em>undefined</em>')
rows.append('<tr><td>%s</td></tr>' % small(grey(', '.join(dump))))
frames.append('''<p>
<table width="100%%" cellspacing=0 cellpadding=0 border=0>
%s</table>''' % '\n'.join(rows))
exception = ['<p>%s: %s' % (strong(str(etype)), str(evalue))]
if type(evalue) is types.InstanceType: if type(evalue) is types.InstanceType:
for name in dir(evalue): for name in dir(evalue):
value = pydoc.html.repr(getattr(evalue, name)) value = pydoc.html.repr(getattr(evalue, name))
exception.append('\n<br>%s%s&nbsp;=\n%s' % (indent, name, value)) exception.append('\n<br>%s%s&nbsp;=\n%s' % (indent, name, value))
import traceback import traceback
plaintrace = ''.join(traceback.format_exception(etype, evalue, etb))
return head + ''.join(frames) + ''.join(exception) + ''' return head + ''.join(frames) + ''.join(exception) + '''
<!-- The above is a description of an error that occurred in a Python program. <!-- The above is a description of an error in a Python program, formatted
It is formatted for display in a Web browser because it appears that for a Web browser because the 'cgitb' module was enabled. In case you
we are running in a CGI environment. In case you are viewing this are not reading this in a Web browser, here is the original traceback:
message outside of a Web browser, here is the original error traceback:
%s %s
--> -->
''' % plaintrace ''' % ''.join(traceback.format_exception(etype, evalue, etb))
class Hook: class Hook:
def __init__(self, display=1, logdir=None): """A hook to replace sys.excepthook that shows tracebacks in HTML."""
def __init__(self, display=1, logdir=None, context=5):
self.display = display # send tracebacks to browser if true self.display = display # send tracebacks to browser if true
self.logdir = logdir # log tracebacks to files if not None self.logdir = logdir # log tracebacks to files if not None
self.context = context # number of source code lines per frame
def __call__(self, etype, evalue, etb): def __call__(self, etype, evalue, etb):
"""This hook can replace sys.excepthook (for Python 2.1 or higher)."""
self.handle((etype, evalue, etb)) self.handle((etype, evalue, etb))
def handle(self, info=None): def handle(self, info=None):
import sys, os import sys
info = info or sys.exc_info() info = info or sys.exc_info()
text = 0
print reset() print reset()
try: try:
doc = html(*info) text, doc = 0, html(info, self.context)
except: # just in case something goes wrong except: # just in case something goes wrong
import traceback import traceback
doc = ''.join(traceback.format_exception(*info)) text, doc = 1, ''.join(traceback.format_exception(*info))
text = 1
if self.display: if self.display:
if text: if text:
doc = doc.replace('&', '&amp;').replace('<', '&lt;') doc = doc.replace('&', '&amp;').replace('<', '&lt;')
print '<pre>', doc, '</pre>' print '<pre>' + doc + '</pre>'
else: else:
print doc print doc
else: else:
print '<p>A problem occurred in a Python script.' print '<p>A problem occurred in a Python script.'
if self.logdir is not None: if self.logdir is not None:
import tempfile import os, tempfile
name = tempfile.mktemp(['.html', '.txt'][text]) name = tempfile.mktemp(['.html', '.txt'][text])
path = os.path.join(self.logdir, os.path.basename(name)) path = os.path.join(self.logdir, os.path.basename(name))
try: try:
file = open(path, 'w') file = open(path, 'w')
file.write(doc) file.write(doc)
file.close() file.close()
print '<p>%s contains the description of this error.' % path print '<p> %s contains the description of this error.' % path
except: except:
print '<p>Tried to write to %s, but failed.' % path print '<p> Tried to save traceback to %s, but failed.' % path
handler = Hook().handle handler = Hook().handle
def enable(display=1, logdir=None): def enable(display=1, logdir=None, context=5):
"""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."""
import sys import sys
sys.excepthook = Hook(display, logdir) sys.excepthook = Hook(display, logdir, context)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment