home *** CD-ROM | disk | FTP | other *** search
Wrap
# Source Generated with Decompyle++ # File: in.pyc (Python 2.6) import inspect import keyword import linecache import os import pydoc import re import string import sys import time import tokenize import traceback import types from inspect import getsourcefile, getfile, getmodule, ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode from IPython import Debugger, PyColorize, ipapi from IPython.ipstruct import Struct from IPython.excolors import exception_colors from IPython.genutils import Term, uniq_stable, error, info INDENT_SIZE = 8 DEFAULT_SCHEME = 'NoColor' def inspect_error(): error('Internal Python error in the inspect module.\nBelow is the traceback from this internal error.\n') def findsource(object): if not getsourcefile(object): pass file = getfile(object) globals_dict = None if inspect.isframe(object): globals_dict = object.f_globals else: module = getmodule(object, file) if module: globals_dict = module.__dict__ lines = linecache.getlines(file, globals_dict) if not lines: raise IOError('could not get source code') lines if ismodule(object): return (lines, 0) if isclass(object): name = object.__name__ pat = re.compile('^(\\s*)class\\s*' + name + '\\b') candidates = [] for i in range(len(lines)): match = pat.match(lines[i]) if match: if lines[i][0] == 'c': return (lines, i) candidates.append((match.group(1), i)) continue lines[i][0] == 'c' if candidates: candidates.sort() return (lines, candidates[0][1]) raise IOError('could not find class definition') isclass(object) if ismethod(object): object = object.im_func if isfunction(object): object = object.func_code if istraceback(object): object = object.tb_frame if isframe(object): object = object.f_code if iscode(object): if not hasattr(object, 'co_firstlineno'): raise IOError('could not find function definition') hasattr(object, 'co_firstlineno') pat = re.compile('^(\\s*def\\s)|(.*(?<!\\w)lambda(:|\\s))|^(\\s*@)') pmatch = pat.match lnum = min(object.co_firstlineno, len(lines)) - 1 while lnum > 0: if pmatch(lines[lnum]): break lnum -= 1 return (lines, lnum) raise IOError('could not find code object') if sys.version_info[:2] >= (2, 5): inspect.findsource = findsource def fix_frame_records_filenames(records): fixed_records = [] for frame, filename, line_no, func_name, lines, index in records: better_fn = frame.f_globals.get('__file__', None) if isinstance(better_fn, str): filename = better_fn fixed_records.append((frame, filename, line_no, func_name, lines, index)) return fixed_records def _fixed_getinnerframes(etb, context = 1, tb_offset = 0): import linecache (LNUM_POS, LINES_POS, INDEX_POS) = (2, 4, 5) records = fix_frame_records_filenames(inspect.getinnerframes(etb, context)) rec_check = records[tb_offset:] try: rname = rec_check[0][1] if rname == '<ipython console>' or rname.endswith('<string>'): return rec_check except IndexError: pass aux = traceback.extract_tb(etb) for file, lnum, _, _ in zip(range(len(records)), aux): maybeStart = lnum - 1 - context // 2 start = max(maybeStart, 0) end = start + context lines = linecache.getlines(file)[start:end] if maybeStart < 0: lines = [ '\n'] * -maybeStart + lines if len(lines) < context: lines += [ '\n'] * (context - len(lines)) buf = list(records[i]) buf[LNUM_POS] = lnum buf[INDEX_POS] = lnum - 1 - start buf[LINES_POS] = lines records[i] = tuple(buf) return records[tb_offset:] _parser = PyColorize.Parser() def _formatTracebackLines(lnum, index, lines, Colors, lvals = None, scheme = None): numbers_width = INDENT_SIZE - 1 res = [] i = lnum - index if scheme is None: ipinst = ipapi.get() if ipinst is not None: scheme = ipinst.IP.rc.colors else: scheme = DEFAULT_SCHEME _line_format = _parser.format2 for line in lines: (new_line, err) = _line_format(line, 'str', scheme) if not err: line = new_line if i == lnum: pad = numbers_width - len(str(i)) if pad >= 3: marker = '-' * (pad - 3) + '-> ' elif pad == 2: marker = '> ' elif pad == 1: marker = '>' else: marker = '' num = marker + str(i) line = '%s%s%s %s%s' % (Colors.linenoEm, num, Colors.line, line, Colors.Normal) else: num = '%*s' % (numbers_width, i) line = '%s%s%s %s' % (Colors.lineno, num, Colors.Normal, line) res.append(line) if lvals and i == lnum: res.append(lvals + '\n') i = i + 1 return res class TBTools: def __init__(self, color_scheme = 'NoColor', call_pdb = False): self.call_pdb = call_pdb self.color_scheme_table = exception_colors() self.set_colors(color_scheme) self.old_scheme = color_scheme if call_pdb: self.pdb = Debugger.Pdb(self.color_scheme_table.active_scheme_name) else: self.pdb = None def set_colors(self, *args, **kw): self.color_scheme_table.set_active_scheme(*args, **kw) self.Colors = self.color_scheme_table.active_colors if hasattr(self, 'pdb') and self.pdb is not None: self.pdb.set_colors(*args, **kw) def color_toggle(self): if self.color_scheme_table.active_scheme_name == 'NoColor': self.color_scheme_table.set_active_scheme(self.old_scheme) self.Colors = self.color_scheme_table.active_colors else: self.old_scheme = self.color_scheme_table.active_scheme_name self.color_scheme_table.set_active_scheme('NoColor') self.Colors = self.color_scheme_table.active_colors class ListTB(TBTools): def __init__(self, color_scheme = 'NoColor'): TBTools.__init__(self, color_scheme = color_scheme, call_pdb = 0) def __call__(self, etype, value, elist): Term.cout.flush() print >>Term.cerr, self.text(etype, value, elist) Term.cerr.flush() def text(self, etype, value, elist, context = 5): Colors = self.Colors out_string = [ '%s%s%s\n' % (Colors.topline, '-' * 60, Colors.Normal)] if elist: out_string.append('Traceback %s(most recent call last)%s:' % (Colors.normalEm, Colors.Normal) + '\n') out_string.extend(self._format_list(elist)) lines = self._format_exception_only(etype, value) for line in lines[:-1]: out_string.append(' ' + line) out_string.append(lines[-1]) return ''.join(out_string) def _format_list(self, extracted_list): Colors = self.Colors list = [] for filename, lineno, name, line in extracted_list[:-1]: 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) if line: item = item + ' %s\n' % line.strip() list.append(item) (filename, lineno, name, line) = extracted_list[-1] 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) if line: item = item + '%s %s%s\n' % (Colors.line, line.strip(), Colors.Normal) list.append(item) return list def _format_exception_only(self, etype, value): have_filedata = False Colors = self.Colors list = [] try: stype = Colors.excName + etype.__name__ + Colors.Normal except AttributeError: stype = etype if value is None: list.append(str(stype) + '\n') elif etype is SyntaxError: try: (filename, lineno, offset, line) = (msg,) except: have_filedata = False have_filedata = True if not filename: filename = '<string>' list.append('%s File %s"%s"%s, line %s%d%s\n' % (Colors.normalEm, Colors.filenameEm, filename, Colors.normalEm, Colors.linenoEm, lineno, Colors.Normal)) if line is not None: i = 0 while i < len(line) and line[i].isspace(): i = i + 1 list.append('%s %s%s\n' % (Colors.line, line.strip(), Colors.Normal)) if offset is not None: s = ' ' for c in line[i:offset - 1]: if c.isspace(): s = s + c continue s = s + ' ' list.append('%s%s^%s\n' % (Colors.caret, s, Colors.Normal)) value = msg s = self._some_str(value) if s: list.append('%s%s:%s %s\n' % (str(stype), Colors.excName, Colors.Normal, s)) else: list.append('%s\n' % str(stype)) if have_filedata: ipinst = ipapi.get() if ipinst is not None: ipinst.IP.hooks.synchronize_with_editor(filename, lineno, 0) return list def _some_str(self, value): try: return str(value) except: return '<unprintable %s object>' % type(value).__name__ class VerboseTB(TBTools): def __init__(self, color_scheme = 'Linux', tb_offset = 0, long_header = 0, call_pdb = 0, include_vars = 1): TBTools.__init__(self, color_scheme = color_scheme, call_pdb = call_pdb) self.tb_offset = tb_offset self.long_header = long_header self.include_vars = include_vars def text(self, etype, evalue, etb, context = 5): try: etype = etype.__name__ except AttributeError: pass Colors = self.Colors ColorsNormal = Colors.Normal col_scheme = self.color_scheme_table.active_scheme_name indent = ' ' * INDENT_SIZE em_normal = '%s\n%s%s' % (Colors.valEm, indent, ColorsNormal) undefined = '%sundefined%s' % (Colors.em, ColorsNormal) exc = '%s%s%s' % (Colors.excName, etype, ColorsNormal) def text_repr(value): try: return pydoc.text.repr(value) except KeyboardInterrupt: raise except: try: return repr(value) except KeyboardInterrupt: raise except: None<EXCEPTION MATCH>KeyboardInterrupt try: name = getattr(value, '__name__', None) if name: return text_repr(name) klass = getattr(value, '__class__', None) if klass: return '%s instance' % text_repr(klass) except KeyboardInterrupt: raise except: None<EXCEPTION MATCH>KeyboardInterrupt return 'UNRECOVERABLE REPR FAILURE' def eqrepr(value, repr = text_repr): return '=%s' % repr(value) def nullrepr(value, repr = text_repr): return '' try: etype = etype.__name__ except AttributeError: (None,) (None,) except: (None,) if self.long_header: pyver = 'Python ' + string.split(sys.version)[0] + ': ' + sys.executable date = time.ctime(time.time()) 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)) 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.' else: head = '%s%s%s\n%s%s' % (Colors.topline, '-' * 75, ColorsNormal, exc, string.rjust('Traceback (most recent call last)', 75 - len(str(etype)))) frames = [] linecache.checkcache() try: records = _fixed_getinnerframes(etb, context, self.tb_offset) except: inspect_error() traceback.print_exc(file = Term.cerr) info('\nUnfortunately, your original traceback can not be constructed.\n') return '' tpl_link = '%s%%s%s' % (Colors.filenameEm, ColorsNormal) tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal) tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % (Colors.vName, Colors.valEm, ColorsNormal) tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal) tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal, Colors.vName, ColorsNormal) tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal) tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal) tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal) abspath = os.path.abspath for frame, file, lnum, func, lines, index in records: try: if not file or abspath(file): pass file = '?' except OSError: pass link = tpl_link % file try: (args, varargs, varkw, locals) = inspect.getargvalues(frame) except: inspect_error() traceback.print_exc(file = Term.cerr) info("\nIPython's exception reporting continues...\n") if func == '?': call = '' elif not self.include_vars or eqrepr: pass var_repr = nullrepr try: call = tpl_call % (func, inspect.formatargvalues(args, varargs, varkw, locals, formatvalue = var_repr)) except KeyError: inspect_error() traceback.print_exc(file = Term.cerr) info("\nIPython's exception reporting continues...\n") call = tpl_call_fail % func names = [] def tokeneater(token_type, token, start, end, line): if token == '.': try: names[-1] += '.' tokeneater.name_cont = True return None except IndexError: pass except: None<EXCEPTION MATCH>IndexError None<EXCEPTION MATCH>IndexError if token_type == tokenize.NAME and token not in keyword.kwlist: if tokeneater.name_cont: names[-1] += token tokeneater.name_cont = False else: names.append(token) elif token_type == tokenize.NEWLINE: raise IndexError tokeneater.name_cont = False def linereader(file = file, lnum = [ lnum], getline = linecache.getline): line = getline(file, lnum[0]) lnum[0] += 1 return line try: tokenize.tokenize(linereader, tokeneater) except IndexError: (None, None) (None, None) except tokenize.TokenError: msg = None _m = 'An unexpected error occurred while tokenizing input\nThe following traceback may be corrupted or invalid\nThe error message is: %s\n' % msg error(_m) except: (None, None) unique_names = uniq_stable(names) lvals = [] if self.include_vars: for name_full in unique_names: name_base = name_full.split('.', 1)[0] if name_base in frame.f_code.co_varnames: name = tpl_local_var % name_full elif frame.f_globals.has_key(name_base): try: value = repr(eval(name_full, frame.f_globals)) value = undefined else: value = undefined name = tpl_global_var % name_full lvals.append(tpl_name_val % (name, value)) if lvals: lvals = '%s%s' % (indent, em_normal.join(lvals)) else: lvals = '' level = '%s %s\n' % (link, call) if index is None: frames.append(level) continue frames.append('%s%s' % (level, ''.join(_formatTracebackLines(lnum, index, lines, Colors, lvals, col_scheme)))) try: (etype_str, evalue_str) = map(str, (etype, evalue)) except: etype = str evalue = sys.exc_info()[:2] (etype_str, evalue_str) = map(str, (etype, evalue)) exception = [ '%s%s%s: %s' % (Colors.excName, etype_str, ColorsNormal, evalue_str)] if type(evalue) is types.InstanceType: try: names = _[1] except: _m = '%sException reporting error (object with broken dir())%s:' exception.append(_m % (Colors.excName, ColorsNormal)) (etype_str, evalue_str) = map(str, sys.exc_info()[:2]) exception.append('%s%s%s: %s' % (Colors.excName, etype_str, ColorsNormal, evalue_str)) names = [] for name in names: value = text_repr(getattr(evalue, name)) exception.append('\n%s%s = %s' % (indent, name, value)) if records: (filepath, lnum) = records[-1][1:3] filepath = os.path.abspath(filepath) ipinst = ipapi.get() if ipinst is not None: ipinst.IP.hooks.synchronize_with_editor(filepath, lnum, 0) return '%s\n\n%s\n%s' % (head, '\n'.join(frames), ''.join(exception[0])) def debugger(self, force = False): if force or self.call_pdb: if self.pdb is None: self.pdb = Debugger.Pdb(self.color_scheme_table.active_scheme_name) dhook = sys.displayhook sys.displayhook = sys.__displayhook__ self.pdb.reset() if hasattr(self, 'tb'): etb = self.tb else: etb = self.tb = sys.last_traceback while self.tb.tb_next is not None: self.tb = self.tb.tb_next try: if etb and etb.tb_next: etb = etb.tb_next self.pdb.botframe = etb.tb_frame self.pdb.interaction(self.tb.tb_frame, self.tb) finally: sys.displayhook = dhook if hasattr(self, 'tb'): del self.tb def handler(self, info = None): if not info: pass (etype, evalue, etb) = sys.exc_info() self.tb = etb Term.cout.flush() print >>Term.cerr, self.text(etype, evalue, etb) Term.cerr.flush() def __call__(self, etype = None, evalue = None, etb = None): if etb is None: self.handler() else: self.handler((etype, evalue, etb)) try: self.debugger() except KeyboardInterrupt: print '\nKeyboardInterrupt' class FormattedTB(VerboseTB, ListTB): def __init__(self, mode = 'Plain', color_scheme = 'Linux', tb_offset = 0, long_header = 0, call_pdb = 0, include_vars = 0): self.valid_modes = [ 'Plain', 'Context', 'Verbose'] self.verbose_modes = self.valid_modes[1:3] VerboseTB.__init__(self, color_scheme, tb_offset, long_header, call_pdb = call_pdb, include_vars = include_vars) self.set_mode(mode) def _extract_tb(self, tb): if tb: return traceback.extract_tb(tb) return None def text(self, etype, value, tb, context = 5, mode = None): if mode is None: mode = self.mode if mode in self.verbose_modes: return VerboseTB.text(self, etype, value, tb, context = 5) linecache.checkcache() elist = self._extract_tb(tb) if len(elist) > self.tb_offset: del elist[:self.tb_offset] return ListTB.text(self, etype, value, elist) def set_mode(self, mode = None): if not mode: new_idx = (self.valid_modes.index(self.mode) + 1) % len(self.valid_modes) self.mode = self.valid_modes[new_idx] elif mode not in self.valid_modes: raise ValueError, 'Unrecognized mode in FormattedTB: <' + mode + '>\nValid modes: ' + str(self.valid_modes) else: self.mode = mode self.include_vars = self.mode == self.valid_modes[2] def plain(self): self.set_mode(self.valid_modes[0]) def context(self): self.set_mode(self.valid_modes[1]) def verbose(self): self.set_mode(self.valid_modes[2]) class AutoFormattedTB(FormattedTB): def __call__(self, etype = None, evalue = None, etb = None, out = None, tb_offset = None): if out is None: out = Term.cerr Term.cout.flush() if tb_offset is not None: tb_offset = self.tb_offset self.tb_offset = tb_offset print >>out, self.text(etype, evalue, etb) self.tb_offset = tb_offset else: print >>out, self.text(etype, evalue, etb) out.flush() try: self.debugger() except KeyboardInterrupt: print '\nKeyboardInterrupt' def text(self, etype = None, value = None, tb = None, context = 5, mode = None): if etype is None: (etype, value, tb) = sys.exc_info() self.tb = tb return FormattedTB.text(self, etype, value, tb, context = 5, mode = mode) class ColorTB(FormattedTB): def __init__(self, color_scheme = 'Linux', call_pdb = 0): FormattedTB.__init__(self, color_scheme = color_scheme, call_pdb = call_pdb) if __name__ == '__main__': def spam(c, .1): (d, e) = .1 x = c + d y = c * d foo(x, y) def foo(a, b, bar = 1): eggs(a, b + bar) def eggs(f, g, z = globals()): h = f + g i = f - g return h / i print '' print '*** Before ***' try: print spam(1, (2, 3)) except: traceback.print_exc() print '' handler = ColorTB() print '*** ColorTB ***' try: print spam(1, (2, 3)) except: apply(handler, sys.exc_info()) print '' handler = VerboseTB() print '*** VerboseTB ***' try: print spam(1, (2, 3)) except: apply(handler, sys.exc_info()) print ''