"""Handle exceptions in CGI scripts by formatting tracebacks into nice HTML. To enable this module, do: import cgitb; cgitb.enable() at the top of your CGI script. The optional arguments to enable() are: display - if true, tracebacks are displayed in the web browser 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 saved, and context is 5. 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 tuple (etype, evalue, etb) just like the value of sys.exc_info().""" __author__ = 'Ka-Ping Yee' __version__ = '$Revision$' def reset(): """Return a string that resets the CGI and browser to a known state.""" return ''' --> --> ''' __UNDEF__ = [] # a special sentinel object def small(text): return '' + text + '' def strong(text): return '' + text + '' def grey(text): return '' + text + '' 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: etype = etype.__name__ pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable date = time.ctime(time.time()) head = '' + pydoc.html.heading( '%s' % str(etype), '#ffffff', '#6622aa', 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.''' indent = '' + small(' ' * 5) + ' ' frames = [] records = inspect.getinnerframes(etb, context) for frame, file, lnum, func, lines, index in records: file = file and os.path.abspath(file) or '?' link = '%s' % (file, pydoc.html.escape(file)) args, varargs, varkw, locals = inspect.getargvalues(frame) 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 = ['%s%s %s' % (' ', link, call)] if index is not None: i = lnum - index for line in lines: num = small(' ' * (5-len(str(i))) + str(i)) + ' ' line = '%s%s' % (num, pydoc.html.preformat(line)) if i in highlight: rows.append('%s' % line) else: rows.append('%s' % 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__: if where == 'global': name = 'global ' + strong(name) elif where == 'local': name = strong(name) else: name = where + strong(name.split('.')[-1]) dump.append('%s = %s' % (name, pydoc.html.repr(value))) else: dump.append(name + ' undefined') rows.append('%s' % small(grey(', '.join(dump)))) frames.append('''

%s
''' % '\n'.join(rows)) exception = ['

%s: %s' % (strong(str(etype)), str(evalue))] if type(evalue) is types.InstanceType: for name in dir(evalue): value = pydoc.html.repr(getattr(evalue, name)) exception.append('\n
%s%s =\n%s' % (indent, name, value)) import traceback return head + ''.join(frames) + ''.join(exception) + ''' ''' % ''.join(traceback.format_exception(etype, evalue, etb)) class Hook: """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.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): self.handle((etype, evalue, etb)) def handle(self, info=None): import sys info = info or sys.exc_info() print reset() try: text, doc = 0, html(info, self.context) except: # just in case something goes wrong import traceback text, doc = 1, ''.join(traceback.format_exception(*info)) if self.display: if text: doc = doc.replace('&', '&').replace('<', '<') print '

' + doc + '
' else: print doc else: print '

A problem occurred in a Python script.' if self.logdir is not None: import os, tempfile name = tempfile.mktemp(['.html', '.txt'][text]) path = os.path.join(self.logdir, os.path.basename(name)) try: file = open(path, 'w') file.write(doc) file.close() print '

%s contains the description of this error.' % path except: print '

Tried to save traceback to %s, but failed.' % path handler = Hook().handle 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 sys.excepthook = Hook(display, logdir, context) ꆧވy\0K54[\ I/׃!C ;{!z7s7G8OITWуWT@.7~ ޟ'd@@0>luǘp\z]0xV yf/ܫm00^6xQ6&N8MFnP@svzGcYT <;?c|Z«GӋ5~F 5_P$)A<'ZANAglyXT'jztMr!zJ碵,]NK%Q3J5GKs.[hۺ|{p6TϨXcSGu(RK;0,;M.}v1qӍ \bxygfڝ8N:L?0`4fzQ{e9:^XKڸcg8_ul QF/~?lW96z 0< :]gTfh[2s_eG'=a!i~?#E h`8;AbҪQE&D)b3߳=)Rv점,Rr׷+ii˒s%t1b;n'>rC}1)Ǒ,l!6!b0~rA@fgl3|QJD";5A۾VxnYӥ0,+A81Χ8{"MFU k%`$K{YL(TaFi,ˬ@pX~1 *<^AdASt>~QDHAlOBQ Mq#86-`!8ݾk EKiH렢_Tk+R')69xb:e9f$ I'6H.Ar tM' r^H+0QTXL$ȉp=%|=tbǖ``@.F1 %YB,BiR}ll``] "BS`~TIL7d)r=;1BJp7 {6} b׮黶6N@\xq{߆ nBԆ'j=?tCoؾm'q8v}H:CQ"U:!kS*' [db Uי)Lԟ,QYgU'\ΊOvgz\rERN)% ݡOTĒeqT#gF+.ᢻ2BHw Pɽ -do=,ʓ(* _*n`&r@&*@Pmi:Tx^ywqt@X*kId"Ηk#mh꩔E=lٶH&mIEZ!h^-- ٮHFqldB }=U^g"|B=ist[A51jЕ ғ2{s1/)YЋ%u5>E{weF撔JmE:Ct[nzq ʪr 8 fu=8%x ,GJ"+KR"UCCt٫G*)@U_ZXUTKb]Q C+pzbyP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