home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2010 November / maximum-cd-2010-11.iso / DiscContents / calibre-0.7.13.msi / file_1939 (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2010-08-06  |  21.7 KB  |  770 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. import inspect
  5. import keyword
  6. import linecache
  7. import os
  8. import pydoc
  9. import re
  10. import string
  11. import sys
  12. import time
  13. import tokenize
  14. import traceback
  15. import types
  16. from inspect import getsourcefile, getfile, getmodule, ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode
  17. from IPython import Debugger, PyColorize, ipapi
  18. from IPython.ipstruct import Struct
  19. from IPython.excolors import exception_colors
  20. from IPython.genutils import Term, uniq_stable, error, info
  21. INDENT_SIZE = 8
  22. DEFAULT_SCHEME = 'NoColor'
  23.  
  24. def inspect_error():
  25.     error('Internal Python error in the inspect module.\nBelow is the traceback from this internal error.\n')
  26.  
  27.  
  28. def findsource(object):
  29.     if not getsourcefile(object):
  30.         pass
  31.     file = getfile(object)
  32.     globals_dict = None
  33.     if inspect.isframe(object):
  34.         globals_dict = object.f_globals
  35.     else:
  36.         module = getmodule(object, file)
  37.         if module:
  38.             globals_dict = module.__dict__
  39.         
  40.     lines = linecache.getlines(file, globals_dict)
  41.     if not lines:
  42.         raise IOError('could not get source code')
  43.     lines
  44.     if ismodule(object):
  45.         return (lines, 0)
  46.     if isclass(object):
  47.         name = object.__name__
  48.         pat = re.compile('^(\\s*)class\\s*' + name + '\\b')
  49.         candidates = []
  50.         for i in range(len(lines)):
  51.             match = pat.match(lines[i])
  52.             if match:
  53.                 if lines[i][0] == 'c':
  54.                     return (lines, i)
  55.                 candidates.append((match.group(1), i))
  56.                 continue
  57.             lines[i][0] == 'c'
  58.         
  59.         if candidates:
  60.             candidates.sort()
  61.             return (lines, candidates[0][1])
  62.         raise IOError('could not find class definition')
  63.     isclass(object)
  64.     if ismethod(object):
  65.         object = object.im_func
  66.     
  67.     if isfunction(object):
  68.         object = object.func_code
  69.     
  70.     if istraceback(object):
  71.         object = object.tb_frame
  72.     
  73.     if isframe(object):
  74.         object = object.f_code
  75.     
  76.     if iscode(object):
  77.         if not hasattr(object, 'co_firstlineno'):
  78.             raise IOError('could not find function definition')
  79.         hasattr(object, 'co_firstlineno')
  80.         pat = re.compile('^(\\s*def\\s)|(.*(?<!\\w)lambda(:|\\s))|^(\\s*@)')
  81.         pmatch = pat.match
  82.         lnum = min(object.co_firstlineno, len(lines)) - 1
  83.         while lnum > 0:
  84.             if pmatch(lines[lnum]):
  85.                 break
  86.             
  87.             lnum -= 1
  88.         return (lines, lnum)
  89.     raise IOError('could not find code object')
  90.  
  91. if sys.version_info[:2] >= (2, 5):
  92.     inspect.findsource = findsource
  93.  
  94.  
  95. def fix_frame_records_filenames(records):
  96.     fixed_records = []
  97.     for frame, filename, line_no, func_name, lines, index in records:
  98.         better_fn = frame.f_globals.get('__file__', None)
  99.         if isinstance(better_fn, str):
  100.             filename = better_fn
  101.         
  102.         fixed_records.append((frame, filename, line_no, func_name, lines, index))
  103.     
  104.     return fixed_records
  105.  
  106.  
  107. def _fixed_getinnerframes(etb, context = 1, tb_offset = 0):
  108.     import linecache
  109.     (LNUM_POS, LINES_POS, INDEX_POS) = (2, 4, 5)
  110.     records = fix_frame_records_filenames(inspect.getinnerframes(etb, context))
  111.     rec_check = records[tb_offset:]
  112.     
  113.     try:
  114.         rname = rec_check[0][1]
  115.         if rname == '<ipython console>' or rname.endswith('<string>'):
  116.             return rec_check
  117.     except IndexError:
  118.         pass
  119.  
  120.     aux = traceback.extract_tb(etb)
  121.     for file, lnum, _, _ in zip(range(len(records)), aux):
  122.         maybeStart = lnum - 1 - context // 2
  123.         start = max(maybeStart, 0)
  124.         end = start + context
  125.         lines = linecache.getlines(file)[start:end]
  126.         if maybeStart < 0:
  127.             lines = [
  128.                 '\n'] * -maybeStart + lines
  129.         
  130.         if len(lines) < context:
  131.             lines += [
  132.                 '\n'] * (context - len(lines))
  133.         
  134.         buf = list(records[i])
  135.         buf[LNUM_POS] = lnum
  136.         buf[INDEX_POS] = lnum - 1 - start
  137.         buf[LINES_POS] = lines
  138.         records[i] = tuple(buf)
  139.     
  140.     return records[tb_offset:]
  141.  
  142. _parser = PyColorize.Parser()
  143.  
  144. def _formatTracebackLines(lnum, index, lines, Colors, lvals = None, scheme = None):
  145.     numbers_width = INDENT_SIZE - 1
  146.     res = []
  147.     i = lnum - index
  148.     if scheme is None:
  149.         ipinst = ipapi.get()
  150.         if ipinst is not None:
  151.             scheme = ipinst.IP.rc.colors
  152.         else:
  153.             scheme = DEFAULT_SCHEME
  154.     
  155.     _line_format = _parser.format2
  156.     for line in lines:
  157.         (new_line, err) = _line_format(line, 'str', scheme)
  158.         if not err:
  159.             line = new_line
  160.         
  161.         if i == lnum:
  162.             pad = numbers_width - len(str(i))
  163.             if pad >= 3:
  164.                 marker = '-' * (pad - 3) + '-> '
  165.             elif pad == 2:
  166.                 marker = '> '
  167.             elif pad == 1:
  168.                 marker = '>'
  169.             else:
  170.                 marker = ''
  171.             num = marker + str(i)
  172.             line = '%s%s%s %s%s' % (Colors.linenoEm, num, Colors.line, line, Colors.Normal)
  173.         else:
  174.             num = '%*s' % (numbers_width, i)
  175.             line = '%s%s%s %s' % (Colors.lineno, num, Colors.Normal, line)
  176.         res.append(line)
  177.         if lvals and i == lnum:
  178.             res.append(lvals + '\n')
  179.         
  180.         i = i + 1
  181.     
  182.     return res
  183.  
  184.  
  185. class TBTools:
  186.     
  187.     def __init__(self, color_scheme = 'NoColor', call_pdb = False):
  188.         self.call_pdb = call_pdb
  189.         self.color_scheme_table = exception_colors()
  190.         self.set_colors(color_scheme)
  191.         self.old_scheme = color_scheme
  192.         if call_pdb:
  193.             self.pdb = Debugger.Pdb(self.color_scheme_table.active_scheme_name)
  194.         else:
  195.             self.pdb = None
  196.  
  197.     
  198.     def set_colors(self, *args, **kw):
  199.         self.color_scheme_table.set_active_scheme(*args, **kw)
  200.         self.Colors = self.color_scheme_table.active_colors
  201.         if hasattr(self, 'pdb') and self.pdb is not None:
  202.             self.pdb.set_colors(*args, **kw)
  203.         
  204.  
  205.     
  206.     def color_toggle(self):
  207.         if self.color_scheme_table.active_scheme_name == 'NoColor':
  208.             self.color_scheme_table.set_active_scheme(self.old_scheme)
  209.             self.Colors = self.color_scheme_table.active_colors
  210.         else:
  211.             self.old_scheme = self.color_scheme_table.active_scheme_name
  212.             self.color_scheme_table.set_active_scheme('NoColor')
  213.             self.Colors = self.color_scheme_table.active_colors
  214.  
  215.  
  216.  
  217. class ListTB(TBTools):
  218.     
  219.     def __init__(self, color_scheme = 'NoColor'):
  220.         TBTools.__init__(self, color_scheme = color_scheme, call_pdb = 0)
  221.  
  222.     
  223.     def __call__(self, etype, value, elist):
  224.         Term.cout.flush()
  225.         print >>Term.cerr, self.text(etype, value, elist)
  226.         Term.cerr.flush()
  227.  
  228.     
  229.     def text(self, etype, value, elist, context = 5):
  230.         Colors = self.Colors
  231.         out_string = [
  232.             '%s%s%s\n' % (Colors.topline, '-' * 60, Colors.Normal)]
  233.         if elist:
  234.             out_string.append('Traceback %s(most recent call last)%s:' % (Colors.normalEm, Colors.Normal) + '\n')
  235.             out_string.extend(self._format_list(elist))
  236.         
  237.         lines = self._format_exception_only(etype, value)
  238.         for line in lines[:-1]:
  239.             out_string.append(' ' + line)
  240.         
  241.         out_string.append(lines[-1])
  242.         return ''.join(out_string)
  243.  
  244.     
  245.     def _format_list(self, extracted_list):
  246.         Colors = self.Colors
  247.         list = []
  248.         for filename, lineno, name, line in extracted_list[:-1]:
  249.             item = '  File %s"%s"%s, line %s%d%s, in %s%s%s\n' % (Colors.filename, filename, Colors.Normal, Colors.lineno, lineno, Colors.Normal, Colors.name, name, Colors.Normal)
  250.             if line:
  251.                 item = item + '    %s\n' % line.strip()
  252.             
  253.             list.append(item)
  254.         
  255.         (filename, lineno, name, line) = extracted_list[-1]
  256.         item = '%s  File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % (Colors.normalEm, Colors.filenameEm, filename, Colors.normalEm, Colors.linenoEm, lineno, Colors.normalEm, Colors.nameEm, name, Colors.normalEm, Colors.Normal)
  257.         if line:
  258.             item = item + '%s    %s%s\n' % (Colors.line, line.strip(), Colors.Normal)
  259.         
  260.         list.append(item)
  261.         return list
  262.  
  263.     
  264.     def _format_exception_only(self, etype, value):
  265.         have_filedata = False
  266.         Colors = self.Colors
  267.         list = []
  268.         
  269.         try:
  270.             stype = Colors.excName + etype.__name__ + Colors.Normal
  271.         except AttributeError:
  272.             stype = etype
  273.  
  274.         if value is None:
  275.             list.append(str(stype) + '\n')
  276.         elif etype is SyntaxError:
  277.             
  278.             try:
  279.                 (filename, lineno, offset, line) = (msg,)
  280.             except:
  281.                 have_filedata = False
  282.  
  283.             have_filedata = True
  284.             if not filename:
  285.                 filename = '<string>'
  286.             
  287.             list.append('%s  File %s"%s"%s, line %s%d%s\n' % (Colors.normalEm, Colors.filenameEm, filename, Colors.normalEm, Colors.linenoEm, lineno, Colors.Normal))
  288.             if line is not None:
  289.                 i = 0
  290.                 while i < len(line) and line[i].isspace():
  291.                     i = i + 1
  292.                 list.append('%s    %s%s\n' % (Colors.line, line.strip(), Colors.Normal))
  293.                 if offset is not None:
  294.                     s = '    '
  295.                     for c in line[i:offset - 1]:
  296.                         if c.isspace():
  297.                             s = s + c
  298.                             continue
  299.                         s = s + ' '
  300.                     
  301.                     list.append('%s%s^%s\n' % (Colors.caret, s, Colors.Normal))
  302.                 
  303.                 value = msg
  304.             
  305.         
  306.         s = self._some_str(value)
  307.         if s:
  308.             list.append('%s%s:%s %s\n' % (str(stype), Colors.excName, Colors.Normal, s))
  309.         else:
  310.             list.append('%s\n' % str(stype))
  311.         if have_filedata:
  312.             ipinst = ipapi.get()
  313.             if ipinst is not None:
  314.                 ipinst.IP.hooks.synchronize_with_editor(filename, lineno, 0)
  315.             
  316.         
  317.         return list
  318.  
  319.     
  320.     def _some_str(self, value):
  321.         
  322.         try:
  323.             return str(value)
  324.         except:
  325.             return '<unprintable %s object>' % type(value).__name__
  326.  
  327.  
  328.  
  329.  
  330. class VerboseTB(TBTools):
  331.     
  332.     def __init__(self, color_scheme = 'Linux', tb_offset = 0, long_header = 0, call_pdb = 0, include_vars = 1):
  333.         TBTools.__init__(self, color_scheme = color_scheme, call_pdb = call_pdb)
  334.         self.tb_offset = tb_offset
  335.         self.long_header = long_header
  336.         self.include_vars = include_vars
  337.  
  338.     
  339.     def text(self, etype, evalue, etb, context = 5):
  340.         
  341.         try:
  342.             etype = etype.__name__
  343.         except AttributeError:
  344.             pass
  345.  
  346.         Colors = self.Colors
  347.         ColorsNormal = Colors.Normal
  348.         col_scheme = self.color_scheme_table.active_scheme_name
  349.         indent = ' ' * INDENT_SIZE
  350.         em_normal = '%s\n%s%s' % (Colors.valEm, indent, ColorsNormal)
  351.         undefined = '%sundefined%s' % (Colors.em, ColorsNormal)
  352.         exc = '%s%s%s' % (Colors.excName, etype, ColorsNormal)
  353.         
  354.         def text_repr(value):
  355.             
  356.             try:
  357.                 return pydoc.text.repr(value)
  358.             except KeyboardInterrupt:
  359.                 raise 
  360.             except:
  361.                 
  362.                 try:
  363.                     return repr(value)
  364.                 except KeyboardInterrupt:
  365.                     raise 
  366.                 except:
  367.                     None<EXCEPTION MATCH>KeyboardInterrupt
  368.                     
  369.                     try:
  370.                         name = getattr(value, '__name__', None)
  371.                         if name:
  372.                             return text_repr(name)
  373.                         klass = getattr(value, '__class__', None)
  374.                         if klass:
  375.                             return '%s instance' % text_repr(klass)
  376.                     except KeyboardInterrupt:
  377.                         raise 
  378.                     except:
  379.                         None<EXCEPTION MATCH>KeyboardInterrupt
  380.                         return 'UNRECOVERABLE REPR FAILURE'
  381.                     
  382.  
  383.                 
  384.  
  385.  
  386.  
  387.         
  388.         def eqrepr(value, repr = text_repr):
  389.             return '=%s' % repr(value)
  390.  
  391.         
  392.         def nullrepr(value, repr = text_repr):
  393.             return ''
  394.  
  395.         
  396.         try:
  397.             etype = etype.__name__
  398.         except AttributeError:
  399.             (None,)
  400.             (None,)
  401.         except:
  402.             (None,)
  403.  
  404.         if self.long_header:
  405.             pyver = 'Python ' + string.split(sys.version)[0] + ': ' + sys.executable
  406.             date = time.ctime(time.time())
  407.             head = '%s%s%s\n%s%s%s\n%s' % (Colors.topline, '-' * 75, ColorsNormal, exc, ' ' * (75 - len(str(etype)) - len(pyver)), pyver, string.rjust(date, 75))
  408.             head += '\nA problem occured executing Python code.  Here is the sequence of function\ncalls leading up to the error, with the most recent (innermost) call last.'
  409.         else:
  410.             head = '%s%s%s\n%s%s' % (Colors.topline, '-' * 75, ColorsNormal, exc, string.rjust('Traceback (most recent call last)', 75 - len(str(etype))))
  411.         frames = []
  412.         linecache.checkcache()
  413.         
  414.         try:
  415.             records = _fixed_getinnerframes(etb, context, self.tb_offset)
  416.         except:
  417.             inspect_error()
  418.             traceback.print_exc(file = Term.cerr)
  419.             info('\nUnfortunately, your original traceback can not be constructed.\n')
  420.             return ''
  421.  
  422.         tpl_link = '%s%%s%s' % (Colors.filenameEm, ColorsNormal)
  423.         tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal)
  424.         tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % (Colors.vName, Colors.valEm, ColorsNormal)
  425.         tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal)
  426.         tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal, Colors.vName, ColorsNormal)
  427.         tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
  428.         tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal)
  429.         tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal)
  430.         abspath = os.path.abspath
  431.         for frame, file, lnum, func, lines, index in records:
  432.             
  433.             try:
  434.                 if not file or abspath(file):
  435.                     pass
  436.                 file = '?'
  437.             except OSError:
  438.                 pass
  439.  
  440.             link = tpl_link % file
  441.             
  442.             try:
  443.                 (args, varargs, varkw, locals) = inspect.getargvalues(frame)
  444.             except:
  445.                 inspect_error()
  446.                 traceback.print_exc(file = Term.cerr)
  447.                 info("\nIPython's exception reporting continues...\n")
  448.  
  449.             if func == '?':
  450.                 call = ''
  451.             elif not self.include_vars or eqrepr:
  452.                 pass
  453.             var_repr = nullrepr
  454.             
  455.             try:
  456.                 call = tpl_call % (func, inspect.formatargvalues(args, varargs, varkw, locals, formatvalue = var_repr))
  457.             except KeyError:
  458.                 inspect_error()
  459.                 traceback.print_exc(file = Term.cerr)
  460.                 info("\nIPython's exception reporting continues...\n")
  461.                 call = tpl_call_fail % func
  462.  
  463.             names = []
  464.             
  465.             def tokeneater(token_type, token, start, end, line):
  466.                 if token == '.':
  467.                     
  468.                     try:
  469.                         names[-1] += '.'
  470.                         tokeneater.name_cont = True
  471.                         return None
  472.                     except IndexError:
  473.                         pass
  474.                     except:
  475.                         None<EXCEPTION MATCH>IndexError
  476.                     
  477.  
  478.                 None<EXCEPTION MATCH>IndexError
  479.                 if token_type == tokenize.NAME and token not in keyword.kwlist:
  480.                     if tokeneater.name_cont:
  481.                         names[-1] += token
  482.                         tokeneater.name_cont = False
  483.                     else:
  484.                         names.append(token)
  485.                 elif token_type == tokenize.NEWLINE:
  486.                     raise IndexError
  487.                 
  488.  
  489.             tokeneater.name_cont = False
  490.             
  491.             def linereader(file = file, lnum = [
  492.                 lnum], getline = linecache.getline):
  493.                 line = getline(file, lnum[0])
  494.                 lnum[0] += 1
  495.                 return line
  496.  
  497.             
  498.             try:
  499.                 tokenize.tokenize(linereader, tokeneater)
  500.             except IndexError:
  501.                 (None, None)
  502.                 (None, None)
  503.             except tokenize.TokenError:
  504.                 msg = None
  505.                 _m = 'An unexpected error occurred while tokenizing input\nThe following traceback may be corrupted or invalid\nThe error message is: %s\n' % msg
  506.                 error(_m)
  507.             except:
  508.                 (None, None)
  509.  
  510.             unique_names = uniq_stable(names)
  511.             lvals = []
  512.             if self.include_vars:
  513.                 for name_full in unique_names:
  514.                     name_base = name_full.split('.', 1)[0]
  515.                     if name_base in frame.f_code.co_varnames:
  516.                         name = tpl_local_var % name_full
  517.                     elif frame.f_globals.has_key(name_base):
  518.                         
  519.                         try:
  520.                             value = repr(eval(name_full, frame.f_globals))
  521.                         value = undefined
  522.  
  523.                     else:
  524.                         value = undefined
  525.                     name = tpl_global_var % name_full
  526.                     lvals.append(tpl_name_val % (name, value))
  527.                 
  528.             
  529.             if lvals:
  530.                 lvals = '%s%s' % (indent, em_normal.join(lvals))
  531.             else:
  532.                 lvals = ''
  533.             level = '%s %s\n' % (link, call)
  534.             if index is None:
  535.                 frames.append(level)
  536.                 continue
  537.             frames.append('%s%s' % (level, ''.join(_formatTracebackLines(lnum, index, lines, Colors, lvals, col_scheme))))
  538.         
  539.         
  540.         try:
  541.             (etype_str, evalue_str) = map(str, (etype, evalue))
  542.         except:
  543.             etype = str
  544.             evalue = sys.exc_info()[:2]
  545.             (etype_str, evalue_str) = map(str, (etype, evalue))
  546.  
  547.         exception = [
  548.             '%s%s%s: %s' % (Colors.excName, etype_str, ColorsNormal, evalue_str)]
  549.         if type(evalue) is types.InstanceType:
  550.             
  551.             try:
  552.                 names = _[1]
  553.             except:
  554.                 _m = '%sException reporting error (object with broken dir())%s:'
  555.                 exception.append(_m % (Colors.excName, ColorsNormal))
  556.                 (etype_str, evalue_str) = map(str, sys.exc_info()[:2])
  557.                 exception.append('%s%s%s: %s' % (Colors.excName, etype_str, ColorsNormal, evalue_str))
  558.                 names = []
  559.  
  560.             for name in names:
  561.                 value = text_repr(getattr(evalue, name))
  562.                 exception.append('\n%s%s = %s' % (indent, name, value))
  563.             
  564.         
  565.         if records:
  566.             (filepath, lnum) = records[-1][1:3]
  567.             filepath = os.path.abspath(filepath)
  568.             ipinst = ipapi.get()
  569.             if ipinst is not None:
  570.                 ipinst.IP.hooks.synchronize_with_editor(filepath, lnum, 0)
  571.             
  572.         
  573.         return '%s\n\n%s\n%s' % (head, '\n'.join(frames), ''.join(exception[0]))
  574.  
  575.     
  576.     def debugger(self, force = False):
  577.         if force or self.call_pdb:
  578.             if self.pdb is None:
  579.                 self.pdb = Debugger.Pdb(self.color_scheme_table.active_scheme_name)
  580.             
  581.             dhook = sys.displayhook
  582.             sys.displayhook = sys.__displayhook__
  583.             self.pdb.reset()
  584.             if hasattr(self, 'tb'):
  585.                 etb = self.tb
  586.             else:
  587.                 etb = self.tb = sys.last_traceback
  588.             while self.tb.tb_next is not None:
  589.                 self.tb = self.tb.tb_next
  590.             
  591.             try:
  592.                 if etb and etb.tb_next:
  593.                     etb = etb.tb_next
  594.                 
  595.                 self.pdb.botframe = etb.tb_frame
  596.                 self.pdb.interaction(self.tb.tb_frame, self.tb)
  597.             finally:
  598.                 sys.displayhook = dhook
  599.  
  600.         
  601.         if hasattr(self, 'tb'):
  602.             del self.tb
  603.         
  604.  
  605.     
  606.     def handler(self, info = None):
  607.         if not info:
  608.             pass
  609.         (etype, evalue, etb) = sys.exc_info()
  610.         self.tb = etb
  611.         Term.cout.flush()
  612.         print >>Term.cerr, self.text(etype, evalue, etb)
  613.         Term.cerr.flush()
  614.  
  615.     
  616.     def __call__(self, etype = None, evalue = None, etb = None):
  617.         if etb is None:
  618.             self.handler()
  619.         else:
  620.             self.handler((etype, evalue, etb))
  621.         
  622.         try:
  623.             self.debugger()
  624.         except KeyboardInterrupt:
  625.             print '\nKeyboardInterrupt'
  626.  
  627.  
  628.  
  629.  
  630. class FormattedTB(VerboseTB, ListTB):
  631.     
  632.     def __init__(self, mode = 'Plain', color_scheme = 'Linux', tb_offset = 0, long_header = 0, call_pdb = 0, include_vars = 0):
  633.         self.valid_modes = [
  634.             'Plain',
  635.             'Context',
  636.             'Verbose']
  637.         self.verbose_modes = self.valid_modes[1:3]
  638.         VerboseTB.__init__(self, color_scheme, tb_offset, long_header, call_pdb = call_pdb, include_vars = include_vars)
  639.         self.set_mode(mode)
  640.  
  641.     
  642.     def _extract_tb(self, tb):
  643.         if tb:
  644.             return traceback.extract_tb(tb)
  645.         return None
  646.  
  647.     
  648.     def text(self, etype, value, tb, context = 5, mode = None):
  649.         if mode is None:
  650.             mode = self.mode
  651.         
  652.         if mode in self.verbose_modes:
  653.             return VerboseTB.text(self, etype, value, tb, context = 5)
  654.         linecache.checkcache()
  655.         elist = self._extract_tb(tb)
  656.         if len(elist) > self.tb_offset:
  657.             del elist[:self.tb_offset]
  658.         
  659.         return ListTB.text(self, etype, value, elist)
  660.  
  661.     
  662.     def set_mode(self, mode = None):
  663.         if not mode:
  664.             new_idx = (self.valid_modes.index(self.mode) + 1) % len(self.valid_modes)
  665.             self.mode = self.valid_modes[new_idx]
  666.         elif mode not in self.valid_modes:
  667.             raise ValueError, 'Unrecognized mode in FormattedTB: <' + mode + '>\nValid modes: ' + str(self.valid_modes)
  668.         else:
  669.             self.mode = mode
  670.         self.include_vars = self.mode == self.valid_modes[2]
  671.  
  672.     
  673.     def plain(self):
  674.         self.set_mode(self.valid_modes[0])
  675.  
  676.     
  677.     def context(self):
  678.         self.set_mode(self.valid_modes[1])
  679.  
  680.     
  681.     def verbose(self):
  682.         self.set_mode(self.valid_modes[2])
  683.  
  684.  
  685.  
  686. class AutoFormattedTB(FormattedTB):
  687.     
  688.     def __call__(self, etype = None, evalue = None, etb = None, out = None, tb_offset = None):
  689.         if out is None:
  690.             out = Term.cerr
  691.         
  692.         Term.cout.flush()
  693.         if tb_offset is not None:
  694.             tb_offset = self.tb_offset
  695.             self.tb_offset = tb_offset
  696.             print >>out, self.text(etype, evalue, etb)
  697.             self.tb_offset = tb_offset
  698.         else:
  699.             print >>out, self.text(etype, evalue, etb)
  700.         out.flush()
  701.         
  702.         try:
  703.             self.debugger()
  704.         except KeyboardInterrupt:
  705.             print '\nKeyboardInterrupt'
  706.  
  707.  
  708.     
  709.     def text(self, etype = None, value = None, tb = None, context = 5, mode = None):
  710.         if etype is None:
  711.             (etype, value, tb) = sys.exc_info()
  712.         
  713.         self.tb = tb
  714.         return FormattedTB.text(self, etype, value, tb, context = 5, mode = mode)
  715.  
  716.  
  717.  
  718. class ColorTB(FormattedTB):
  719.     
  720.     def __init__(self, color_scheme = 'Linux', call_pdb = 0):
  721.         FormattedTB.__init__(self, color_scheme = color_scheme, call_pdb = call_pdb)
  722.  
  723.  
  724. if __name__ == '__main__':
  725.     
  726.     def spam(c, .1):
  727.         (d, e) = .1
  728.         x = c + d
  729.         y = c * d
  730.         foo(x, y)
  731.  
  732.     
  733.     def foo(a, b, bar = 1):
  734.         eggs(a, b + bar)
  735.  
  736.     
  737.     def eggs(f, g, z = globals()):
  738.         h = f + g
  739.         i = f - g
  740.         return h / i
  741.  
  742.     print ''
  743.     print '*** Before ***'
  744.     
  745.     try:
  746.         print spam(1, (2, 3))
  747.     except:
  748.         traceback.print_exc()
  749.  
  750.     print ''
  751.     handler = ColorTB()
  752.     print '*** ColorTB ***'
  753.     
  754.     try:
  755.         print spam(1, (2, 3))
  756.     except:
  757.         apply(handler, sys.exc_info())
  758.  
  759.     print ''
  760.     handler = VerboseTB()
  761.     print '*** VerboseTB ***'
  762.     
  763.     try:
  764.         print spam(1, (2, 3))
  765.     except:
  766.         apply(handler, sys.exc_info())
  767.  
  768.     print ''
  769.  
  770.