Back to index

python3.2  3.2.2
Classes | Functions | Variables
cgitb Namespace Reference

Classes

class  Hook

Functions

def reset
def small
def strong
def grey
def lookup
def scanvars
def html
def text
def enable

Variables

list __UNDEF__ = []
tuple handler = Hook()

Detailed Description

More comprehensive traceback formatting for Python scripts.

To enable this module, do:

    import cgitb; cgitb.enable()

at the top of your 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
    format      - 'text' or 'html' controls the output format

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)

Alternatively, if you have caught an exception and want cgitb to display it
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.

Function Documentation

def cgitb.enable (   display = 1,
  logdir = None,
  context = 5,
  format = "html" 
)
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.

Definition at line 309 of file cgitb.py.

00309 
00310 def enable(display=1, logdir=None, context=5, format="html"):
00311     """Install an exception handler that formats tracebacks as HTML.
00312 
00313     The optional argument 'display' can be set to 0 to suppress sending the
00314     traceback to the browser, and 'logdir' can be set to a directory to cause
00315     tracebacks to be written to files there."""
00316     sys.excepthook = Hook(display=display, logdir=logdir,
00317                           context=context, format=format)

Here is the caller graph for this function:

def cgitb.grey (   text)

Definition at line 59 of file cgitb.py.

00059 
00060 def grey(text):
00061     if text:
00062         return '<font color="#909090">' + text + '</font>'
00063     else:
00064         return ''

Here is the caller graph for this function:

def cgitb.html (   einfo,
  context = 5 
)
Return a nice HTML document describing a given traceback.

Definition at line 102 of file cgitb.py.

00102 
00103 def html(einfo, context=5):
00104     """Return a nice HTML document describing a given traceback."""
00105     etype, evalue, etb = einfo
00106     if isinstance(etype, type):
00107         etype = etype.__name__
00108     pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
00109     date = time.ctime(time.time())
00110     head = '<body bgcolor="#f0f0f8">' + pydoc.html.heading(
00111         '<big><big>%s</big></big>' %
00112         strong(pydoc.html.escape(str(etype))),
00113         '#ffffff', '#6622aa', pyver + '<br>' + date) + '''
00114 <p>A problem occurred in a Python script.  Here is the sequence of
00115 function calls leading up to the error, in the order they occurred.</p>'''
00116 
00117     indent = '<tt>' + small('&nbsp;' * 5) + '&nbsp;</tt>'
00118     frames = []
00119     records = inspect.getinnerframes(etb, context)
00120     for frame, file, lnum, func, lines, index in records:
00121         if file:
00122             file = os.path.abspath(file)
00123             link = '<a href="file://%s">%s</a>' % (file, pydoc.html.escape(file))
00124         else:
00125             file = link = '?'
00126         args, varargs, varkw, locals = inspect.getargvalues(frame)
00127         call = ''
00128         if func != '?':
00129             call = 'in ' + strong(func) + \
00130                 inspect.formatargvalues(args, varargs, varkw, locals,
00131                     formatvalue=lambda value: '=' + pydoc.html.repr(value))
00132 
00133         highlight = {}
00134         def reader(lnum=[lnum]):
00135             highlight[lnum[0]] = 1
00136             try: return linecache.getline(file, lnum[0])
00137             finally: lnum[0] += 1
00138         vars = scanvars(reader, frame, locals)
00139 
00140         rows = ['<tr><td bgcolor="#d8bbff">%s%s %s</td></tr>' %
00141                 ('<big>&nbsp;</big>', link, call)]
00142         if index is not None:
00143             i = lnum - index
00144             for line in lines:
00145                 num = small('&nbsp;' * (5-len(str(i))) + str(i)) + '&nbsp;'
00146                 if i in highlight:
00147                     line = '<tt>=&gt;%s%s</tt>' % (num, pydoc.html.preformat(line))
00148                     rows.append('<tr><td bgcolor="#ffccee">%s</td></tr>' % line)
00149                 else:
00150                     line = '<tt>&nbsp;&nbsp;%s%s</tt>' % (num, pydoc.html.preformat(line))
00151                     rows.append('<tr><td>%s</td></tr>' % grey(line))
00152                 i += 1
00153 
00154         done, dump = {}, []
00155         for name, where, value in vars:
00156             if name in done: continue
00157             done[name] = 1
00158             if value is not __UNDEF__:
00159                 if where in ('global', 'builtin'):
00160                     name = ('<em>%s</em> ' % where) + strong(name)
00161                 elif where == 'local':
00162                     name = strong(name)
00163                 else:
00164                     name = where + strong(name.split('.')[-1])
00165                 dump.append('%s&nbsp;= %s' % (name, pydoc.html.repr(value)))
00166             else:
00167                 dump.append(name + ' <em>undefined</em>')
00168 
00169         rows.append('<tr><td>%s</td></tr>' % small(grey(', '.join(dump))))
00170         frames.append('''
00171 <table width="100%%" cellspacing=0 cellpadding=0 border=0>
00172 %s</table>''' % '\n'.join(rows))
00173 
00174     exception = ['<p>%s: %s' % (strong(pydoc.html.escape(str(etype))),
00175                                 pydoc.html.escape(str(evalue)))]
00176     for name in dir(evalue):
00177         if name[:1] == '_': continue
00178         value = pydoc.html.repr(getattr(evalue, name))
00179         exception.append('\n<br>%s%s&nbsp;=\n%s' % (indent, name, value))
00180 
00181     return head + ''.join(frames) + ''.join(exception) + '''
00182 
00183 
00184 <!-- The above is a description of an error in a Python program, formatted
00185      for a Web browser because the 'cgitb' module was enabled.  In case you
00186      are not reading this in a Web browser, here is the original traceback:
00187 
00188 %s
00189 -->
00190 ''' % pydoc.html.escape(
00191           ''.join(traceback.format_exception(etype, evalue, etb)))

Here is the call graph for this function:

def cgitb.lookup (   name,
  frame,
  locals 
)
Find the value for a given name in the given environment.

Definition at line 65 of file cgitb.py.

00065 
00066 def lookup(name, frame, locals):
00067     """Find the value for a given name in the given environment."""
00068     if name in locals:
00069         return 'local', locals[name]
00070     if name in frame.f_globals:
00071         return 'global', frame.f_globals[name]
00072     if '__builtins__' in frame.f_globals:
00073         builtins = frame.f_globals['__builtins__']
00074         if type(builtins) is type({}):
00075             if name in builtins:
00076                 return 'builtin', builtins[name]
00077         else:
00078             if hasattr(builtins, name):
00079                 return 'builtin', getattr(builtins, name)
00080     return None, __UNDEF__

Here is the call graph for this function:

Here is the caller graph for this function:

def cgitb.reset ( )
Return a string that resets the CGI and browser to a known state.

Definition at line 36 of file cgitb.py.

00036 
00037 def reset():
00038     """Return a string that resets the CGI and browser to a known state."""
00039     return '''<!--: spam
00040 Content-Type: text/html
00041 
00042 <body bgcolor="#f0f0f8"><font color="#f0f0f8" size="-5"> -->
00043 <body bgcolor="#f0f0f8"><font color="#f0f0f8" size="-5"> --> -->
00044 </font> </font> </font> </script> </object> </blockquote> </pre>
00045 </table> </table> </table> </table> </table> </font> </font> </font>'''

Here is the caller graph for this function:

def cgitb.scanvars (   reader,
  frame,
  locals 
)
Scan one logical line of Python and look up values of variables used.

Definition at line 81 of file cgitb.py.

00081 
00082 def scanvars(reader, frame, locals):
00083     """Scan one logical line of Python and look up values of variables used."""
00084     vars, lasttoken, parent, prefix, value = [], None, None, '', __UNDEF__
00085     for ttype, token, start, end, line in tokenize.generate_tokens(reader):
00086         if ttype == tokenize.NEWLINE: break
00087         if ttype == tokenize.NAME and token not in keyword.kwlist:
00088             if lasttoken == '.':
00089                 if parent is not __UNDEF__:
00090                     value = getattr(parent, token, __UNDEF__)
00091                     vars.append((prefix + token, prefix, value))
00092             else:
00093                 where, value = lookup(token, frame, locals)
00094                 vars.append((token, where, value))
00095         elif token == '.':
00096             prefix += lasttoken + '.'
00097             parent = value
00098         else:
00099             parent, prefix = None, ''
00100         lasttoken = token
00101     return vars

Here is the call graph for this function:

Here is the caller graph for this function:

def cgitb.small (   text)

Definition at line 47 of file cgitb.py.

00047 
00048 def small(text):
00049     if text:
00050         return '<small>' + text + '</small>'
00051     else:
00052         return ''

Here is the caller graph for this function:

def cgitb.strong (   text)

Definition at line 53 of file cgitb.py.

00053 
00054 def strong(text):
00055     if text:
00056         return '<strong>' + text + '</strong>'
00057     else:
00058         return ''

Here is the caller graph for this function:

def cgitb.text (   einfo,
  context = 5 
)
Return a plain text document describing a given traceback.

Definition at line 192 of file cgitb.py.

00192 
00193 def text(einfo, context=5):
00194     """Return a plain text document describing a given traceback."""
00195     etype, evalue, etb = einfo
00196     if isinstance(etype, type):
00197         etype = etype.__name__
00198     pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
00199     date = time.ctime(time.time())
00200     head = "%s\n%s\n%s\n" % (str(etype), pyver, date) + '''
00201 A problem occurred in a Python script.  Here is the sequence of
00202 function calls leading up to the error, in the order they occurred.
00203 '''
00204 
00205     frames = []
00206     records = inspect.getinnerframes(etb, context)
00207     for frame, file, lnum, func, lines, index in records:
00208         file = file and os.path.abspath(file) or '?'
00209         args, varargs, varkw, locals = inspect.getargvalues(frame)
00210         call = ''
00211         if func != '?':
00212             call = 'in ' + func + \
00213                 inspect.formatargvalues(args, varargs, varkw, locals,
00214                     formatvalue=lambda value: '=' + pydoc.text.repr(value))
00215 
00216         highlight = {}
00217         def reader(lnum=[lnum]):
00218             highlight[lnum[0]] = 1
00219             try: return linecache.getline(file, lnum[0])
00220             finally: lnum[0] += 1
00221         vars = scanvars(reader, frame, locals)
00222 
00223         rows = [' %s %s' % (file, call)]
00224         if index is not None:
00225             i = lnum - index
00226             for line in lines:
00227                 num = '%5d ' % i
00228                 rows.append(num+line.rstrip())
00229                 i += 1
00230 
00231         done, dump = {}, []
00232         for name, where, value in vars:
00233             if name in done: continue
00234             done[name] = 1
00235             if value is not __UNDEF__:
00236                 if where == 'global': name = 'global ' + name
00237                 elif where != 'local': name = where + name.split('.')[-1]
00238                 dump.append('%s = %s' % (name, pydoc.text.repr(value)))
00239             else:
00240                 dump.append(name + ' undefined')
00241 
00242         rows.append('\n'.join(dump))
00243         frames.append('\n%s\n' % '\n'.join(rows))
00244 
00245     exception = ['%s: %s' % (str(etype), str(evalue))]
00246     for name in dir(evalue):
00247         value = pydoc.text.repr(getattr(evalue, name))
00248         exception.append('\n%s%s = %s' % (" "*4, name, value))
00249 
00250     return head + ''.join(frames) + ''.join(exception) + '''
00251 
00252 The above is a description of an error in a Python program.  Here is
00253 the original traceback:
00254 
00255 %s
00256 ''' % ''.join(traceback.format_exception(etype, evalue, etb))

Here is the call graph for this function:


Variable Documentation

list cgitb.__UNDEF__ = []

Definition at line 46 of file cgitb.py.

tuple cgitb.handler = Hook()

Definition at line 308 of file cgitb.py.