home *** CD-ROM | disk | FTP | other *** search
/ GameStar 2006 January / Gamestar_80_2006-01_dvd.iso / Dema / Civilization4 / data1.cab / Civ4DemoComponent / Assets / Python / System / cgitb.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2005-11-09  |  12.2 KB  |  362 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.4)
  3.  
  4. """More comprehensive traceback formatting for Python scripts.
  5.  
  6. To enable this module, do:
  7.  
  8.     import cgitb; cgitb.enable()
  9.  
  10. at the top of your script.  The optional arguments to enable() are:
  11.  
  12.     display     - if true, tracebacks are displayed in the web browser
  13.     logdir      - if set, tracebacks are written to files in this directory
  14.     context     - number of lines of source code to show for each stack frame
  15.     format      - 'text' or 'html' controls the output format
  16.  
  17. By default, tracebacks are displayed but not saved, the context is 5 lines
  18. and the output format is 'html' (for backwards compatibility with the
  19. original use of this module)
  20.  
  21. Alternatively, if you have caught an exception and want cgitb to display it
  22. for you, call cgitb.handler().  The optional argument to handler() is a
  23. 3-item tuple (etype, evalue, etb) just like the value of sys.exc_info().
  24. The default handler displays output as HTML.
  25. """
  26. __author__ = 'Ka-Ping Yee'
  27. __version__ = '$Revision: 1.15 $'
  28. import sys
  29.  
  30. def reset():
  31.     '''Return a string that resets the CGI and browser to a known state.'''
  32.     return '<!--: spam\nContent-Type: text/html\n\n<body bgcolor="#f0f0f8"><font color="#f0f0f8" size="-5"> -->\n<body bgcolor="#f0f0f8"><font color="#f0f0f8" size="-5"> --> -->\n</font> </font> </font> </script> </object> </blockquote> </pre>\n</table> </table> </table> </table> </table> </font> </font> </font>'
  33.  
  34. __UNDEF__ = []
  35.  
  36. def small(text):
  37.     if text:
  38.         return '<small>' + text + '</small>'
  39.     else:
  40.         return ''
  41.  
  42.  
  43. def strong(text):
  44.     if text:
  45.         return '<strong>' + text + '</strong>'
  46.     else:
  47.         return ''
  48.  
  49.  
  50. def grey(text):
  51.     if text:
  52.         return '<font color="#909090">' + text + '</font>'
  53.     else:
  54.         return ''
  55.  
  56.  
  57. def lookup(name, frame, locals):
  58.     '''Find the value for a given name in the given environment.'''
  59.     if name in locals:
  60.         return ('local', locals[name])
  61.     
  62.     if name in frame.f_globals:
  63.         return ('global', frame.f_globals[name])
  64.     
  65.     if '__builtins__' in frame.f_globals:
  66.         builtins = frame.f_globals['__builtins__']
  67.         if type(builtins) is type({ }):
  68.             if name in builtins:
  69.                 return ('builtin', builtins[name])
  70.             
  71.         elif hasattr(builtins, name):
  72.             return ('builtin', getattr(builtins, name))
  73.         
  74.     
  75.     return (None, __UNDEF__)
  76.  
  77.  
  78. def scanvars(reader, frame, locals):
  79.     '''Scan one logical line of Python and look up values of variables used.'''
  80.     import tokenize
  81.     import keyword
  82.     (vars, lasttoken, parent, prefix, value) = ([], None, None, '', __UNDEF__)
  83.     for ttype, token, start, end, line in tokenize.generate_tokens(reader):
  84.         if ttype == tokenize.NEWLINE:
  85.             break
  86.         
  87.         if ttype == tokenize.NAME and token not in keyword.kwlist:
  88.             if lasttoken == '.':
  89.                 if parent is not __UNDEF__:
  90.                     value = getattr(parent, token, __UNDEF__)
  91.                     vars.append((prefix + token, prefix, value))
  92.                 
  93.             else:
  94.                 (where, value) = lookup(token, frame, locals)
  95.                 vars.append((token, where, value))
  96.         elif token == '.':
  97.             prefix += lasttoken + '.'
  98.             parent = value
  99.         else:
  100.             (parent, prefix) = (None, '')
  101.         lasttoken = token
  102.     
  103.     return vars
  104.  
  105.  
  106. def html(.0, context = 5):
  107.     '''Return a nice HTML document describing a given traceback.'''
  108.     (etype, evalue, etb) = .0
  109.     import os
  110.     import types
  111.     import time
  112.     import traceback
  113.     import linecache
  114.     import inspect
  115.     import pydoc
  116.     if type(etype) is types.ClassType:
  117.         etype = etype.__name__
  118.     
  119.     pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
  120.     date = time.ctime(time.time())
  121.     head = '<body bgcolor="#f0f0f8">' + pydoc.html.heading('<big><big>%s</big></big>' % strong(pydoc.html.escape(str(etype))), '#ffffff', '#6622aa', pyver + '<br>' + date) + '\n<p>A problem occurred in a Python script.  Here is the sequence of\nfunction calls leading up to the error, in the order they occurred.</p>'
  122.     indent = '<tt>' + small(' ' * 5) + ' </tt>'
  123.     frames = []
  124.     records = inspect.getinnerframes(etb, context)
  125.     for frame, file, lnum, func, lines, index in records:
  126.         if not file or os.path.abspath(file):
  127.             pass
  128.         file = '?'
  129.         link = '<a href="file://%s">%s</a>' % (file, pydoc.html.escape(file))
  130.         (args, varargs, varkw, locals) = inspect.getargvalues(frame)
  131.         call = ''
  132.         if func != '?':
  133.             call = 'in ' + strong(func) + inspect.formatargvalues(args, varargs, varkw, locals, formatvalue = (lambda value: '=' + pydoc.html.repr(value)))
  134.         
  135.         highlight = { }
  136.         
  137.         def reader(lnum = [
  138.             lnum]):
  139.             highlight[lnum[0]] = 1
  140.             
  141.             try:
  142.                 return linecache.getline(file, lnum[0])
  143.             finally:
  144.                 lnum[0] += 1
  145.  
  146.  
  147.         vars = scanvars(reader, frame, locals)
  148.         rows = [
  149.             '<tr><td bgcolor="#d8bbff">%s%s %s</td></tr>' % ('<big> </big>', link, call)]
  150.         if index is not None:
  151.             i = lnum - index
  152.             for line in lines:
  153.                 num = small(' ' * (5 - len(str(i))) + str(i)) + ' '
  154.                 line = '<tt>%s%s</tt>' % (num, pydoc.html.preformat(line))
  155.                 if i in highlight:
  156.                     rows.append('<tr><td bgcolor="#ffccee">%s</td></tr>' % line)
  157.                 else:
  158.                     rows.append('<tr><td>%s</td></tr>' % grey(line))
  159.                 i += 1
  160.             
  161.         
  162.         done = { }
  163.         dump = []
  164.         for name, where, value in vars:
  165.             if name in done:
  166.                 continue
  167.             
  168.             done[name] = 1
  169.             if value is not __UNDEF__:
  170.                 if where in [
  171.                     'global',
  172.                     'builtin']:
  173.                     name = '<em>%s</em> ' % where + strong(name)
  174.                 elif where == 'local':
  175.                     name = strong(name)
  176.                 else:
  177.                     name = where + strong(name.split('.')[-1])
  178.                 dump.append('%s = %s' % (name, pydoc.html.repr(value)))
  179.                 continue
  180.             dump.append(name + ' <em>undefined</em>')
  181.         
  182.         rows.append('<tr><td>%s</td></tr>' % small(grey(', '.join(dump))))
  183.         frames.append('\n<table width="100%%" cellspacing=0 cellpadding=0 border=0>\n%s</table>' % '\n'.join(rows))
  184.     
  185.     exception = [
  186.         '<p>%s: %s' % (strong(pydoc.html.escape(str(etype))), pydoc.html.escape(str(evalue)))]
  187.     if type(evalue) is types.InstanceType:
  188.         for name in dir(evalue):
  189.             if name[:1] == '_':
  190.                 continue
  191.             
  192.             value = pydoc.html.repr(getattr(evalue, name))
  193.             exception.append('\n<br>%s%s =\n%s' % (indent, name, value))
  194.         
  195.     
  196.     import traceback
  197.     return head + ''.join(frames) + ''.join(exception) + "\n\n\n<!-- The above is a description of an error in a Python program, formatted\n     for a Web browser because the 'cgitb' module was enabled.  In case you\n     are not reading this in a Web browser, here is the original traceback:\n\n%s\n-->\n" % ''.join(traceback.format_exception(etype, evalue, etb))
  198.  
  199.  
  200. def text(.0, context = 5):
  201.     '''Return a plain text document describing a given traceback.'''
  202.     (etype, evalue, etb) = .0
  203.     import os
  204.     import types
  205.     import time
  206.     import traceback
  207.     import linecache
  208.     import inspect
  209.     import pydoc
  210.     if type(etype) is types.ClassType:
  211.         etype = etype.__name__
  212.     
  213.     pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
  214.     date = time.ctime(time.time())
  215.     head = '%s\n%s\n%s\n' % (str(etype), pyver, date) + '\nA problem occurred in a Python script.  Here is the sequence of\nfunction calls leading up to the error, in the order they occurred.\n'
  216.     frames = []
  217.     records = inspect.getinnerframes(etb, context)
  218.     for frame, file, lnum, func, lines, index in records:
  219.         if not file or os.path.abspath(file):
  220.             pass
  221.         file = '?'
  222.         (args, varargs, varkw, locals) = inspect.getargvalues(frame)
  223.         call = ''
  224.         if func != '?':
  225.             call = 'in ' + func + inspect.formatargvalues(args, varargs, varkw, locals, formatvalue = (lambda value: '=' + pydoc.text.repr(value)))
  226.         
  227.         highlight = { }
  228.         
  229.         def reader(lnum = [
  230.             lnum]):
  231.             highlight[lnum[0]] = 1
  232.             
  233.             try:
  234.                 return linecache.getline(file, lnum[0])
  235.             finally:
  236.                 lnum[0] += 1
  237.  
  238.  
  239.         vars = scanvars(reader, frame, locals)
  240.         rows = [
  241.             ' %s %s' % (file, call)]
  242.         if index is not None:
  243.             i = lnum - index
  244.             for line in lines:
  245.                 num = '%5d ' % i
  246.                 rows.append(num + line.rstrip())
  247.                 i += 1
  248.             
  249.         
  250.         done = { }
  251.         dump = []
  252.         for name, where, value in vars:
  253.             if name in done:
  254.                 continue
  255.             
  256.             done[name] = 1
  257.             if value is not __UNDEF__:
  258.                 if where == 'global':
  259.                     name = 'global ' + name
  260.                 elif where != 'local':
  261.                     name = where + name.split('.')[-1]
  262.                 
  263.                 dump.append('%s = %s' % (name, pydoc.text.repr(value)))
  264.                 continue
  265.             dump.append(name + ' undefined')
  266.         
  267.         rows.append('\n'.join(dump))
  268.         frames.append('\n%s\n' % '\n'.join(rows))
  269.     
  270.     exception = [
  271.         '%s: %s' % (str(etype), str(evalue))]
  272.     if type(evalue) is types.InstanceType:
  273.         for name in dir(evalue):
  274.             value = pydoc.text.repr(getattr(evalue, name))
  275.             exception.append('\n%s%s = %s' % (' ' * 4, name, value))
  276.         
  277.     
  278.     import traceback
  279.     return head + ''.join(frames) + ''.join(exception) + '\n\nThe above is a description of an error in a Python program.  Here is\nthe original traceback:\n\n%s\n' % ''.join(traceback.format_exception(etype, evalue, etb))
  280.  
  281.  
  282. class Hook:
  283.     '''A hook to replace sys.excepthook that shows tracebacks in HTML.'''
  284.     
  285.     def __init__(self, display = 1, logdir = None, context = 5, file = None, format = 'html'):
  286.         self.display = display
  287.         self.logdir = logdir
  288.         self.context = context
  289.         if not file:
  290.             pass
  291.         self.file = sys.stdout
  292.         self.format = format
  293.  
  294.     
  295.     def __call__(self, etype, evalue, etb):
  296.         self.handle((etype, evalue, etb))
  297.  
  298.     
  299.     def handle(self, info = None):
  300.         if not info:
  301.             pass
  302.         info = sys.exc_info()
  303.         if self.format == 'html':
  304.             self.file.write(reset())
  305.         
  306.         if not self.format == 'html' or html:
  307.             pass
  308.         formatter = text
  309.         plain = False
  310.         
  311.         try:
  312.             doc = formatter(info, self.context)
  313.         except:
  314.             import traceback
  315.             doc = ''.join(traceback.format_exception(*info))
  316.             plain = True
  317.  
  318.         if self.display:
  319.             if plain:
  320.                 doc = doc.replace('&', '&').replace('<', '<')
  321.                 self.file.write('<pre>' + doc + '</pre>\n')
  322.             else:
  323.                 self.file.write(doc + '\n')
  324.         else:
  325.             self.file.write('<p>A problem occurred in a Python script.\n')
  326.         if self.logdir is not None:
  327.             import os
  328.             import tempfile
  329.             suffix = [
  330.                 '.txt',
  331.                 '.html'][self.format == 'html']
  332.             (fd, path) = tempfile.mkstemp(suffix = suffix, dir = self.logdir)
  333.             
  334.             try:
  335.                 file = os.fdopen(fd, 'w')
  336.                 file.write(doc)
  337.                 file.close()
  338.                 msg = '<p> %s contains the description of this error.' % path
  339.             except:
  340.                 msg = '<p> Tried to save traceback to %s, but failed.' % path
  341.  
  342.             self.file.write(msg + '\n')
  343.         
  344.         
  345.         try:
  346.             self.file.flush()
  347.         except:
  348.             pass
  349.  
  350.  
  351.  
  352. handler = Hook().handle
  353.  
  354. def enable(display = 1, logdir = None, context = 5, format = 'html'):
  355.     """Install an exception handler that formats tracebacks as HTML.
  356.  
  357.     The optional argument 'display' can be set to 0 to suppress sending the
  358.     traceback to the browser, and 'logdir' can be set to a directory to cause
  359.     tracebacks to be written to files there."""
  360.     sys.excepthook = Hook(display = display, logdir = logdir, context = context, format = format)
  361.  
  362.