Extract trace back information into a list of dictionaries.

    :param tb: traceback
    :return: list of dicts containing filepath, line, module, code, traceback level and source code for tracebacks
491603
def analyze_traceback(tb, inspection_level=None, limit=None):
    
    info = []
    tb_level = tb
    extracted_tb = traceback.extract_tb(tb, limit=limit)
    for ii, (filepath, line, module, code) in enumerate(extracted_tb):
        func_source, func_lineno = inspect.getsourcelines(tb_level.tb_frame)

        d = {"File": filepath,
             "Error Line Number": line,
             "Module": module,
             "Error Line": code,
             "Module Line Number": func_lineno,
             "Custom Inspection": {},
             "Source Code": ''}
        if inspection_level is None or len(extracted_tb) - ii <= inspection_level:
            # Perform advanced inspection on the last `inspection_level` tracebacks.
            d['Source Code'] = ''.join(func_source)
            d['Local Variables'] = get_local_references(tb_level)
            d['Object Variables'] = get_object_references(tb_level, d['Source Code'])
        tb_level = getattr(tb_level, 'tb_next', None)
        info.append(d)

    return info
601518
def missing_input_files(self):
        
        missing = self.check_input_files(return_found=False)
        ret_dict = {}
        for miss_file in missing:
            ret_dict[miss_file] = [self.linkname]
        return ret_dict
686404
def traceback_string():
    
    tb_string = None
    exc_type, exc_value, exc_traceback = traceback.sys.exc_info()
    if exc_type is not None:
        display_lines_list = [str(exc_value)] + traceback.format_tb(exc_traceback)
        tb_string = "\n".join(display_lines_list)
    return tb_string
78685
def _get_traceback_no_io():
    
    try:
        module = load_module(str("_traceback_no_io"), traceback)
    except NotImplementedError:
        # Can't fix the I/O problem, oh well:
        return traceback

    class FakeLineCache(object):
        def checkcache(self, *args, **kwargs):
            None

        def getline(self, *args, **kwargs):
            return ""

        def lazycache(self, *args, **kwargs):
            return None

    module.linecache = FakeLineCache()
    return module
877648
def _unicode_decode_extracted_tb(extracted_tb):
    """"""
    return [(_decode(file), line_number, _decode(function), _decode(text))
            for file, line_number, function, text in extracted_tb]
589588
def translate_exception(exc_info, initial_skip=0):
    
    tb = exc_info[2]
    frames = []

    # skip some internal frames if wanted
    for x in xrange(initial_skip):
        if tb is not None:
            tb = tb.tb_next
    initial_tb = tb

    while tb is not None:
        # skip frames decorated with @internalcode.  These are internal
        # calls we can't avoid and that are useless in template debugging
        # output.
        if tb.tb_frame.f_code in internal_code:
            tb = tb.tb_next
            continue

        # save a reference to the next frame if we override the current
        # one with a faked one.
        next = tb.tb_next

        # fake template exceptions
        template = tb.tb_frame.f_globals.get('__jinja_template__')
        if template is not None:
            lineno = template.get_corresponding_lineno(tb.tb_lineno)
            tb = fake_exc_info(exc_info[:2] + (tb,), template.filename,
                               lineno)[2]

        frames.append(TracebackFrameProxy(tb))
        tb = next

    # if we don't have any exceptions in the frames left, we have to
    # reraise it unchanged.
    # XXX: can we backup here?  when could this happen?
    if not frames:
        raise exc_info[0], exc_info[1], exc_info[2]

    traceback = ProcessedTraceback(exc_info[0], exc_info[1], frames)
    if tb_set_next is not None:
        traceback.chain_frames()
    return traceback
1066342
def trace():
    
    import traceback
    import sys
    tb = sys.exc_info()[2]
    tbinfo = traceback.format_tb(tb)[0]
    # script name + line number
    line = tbinfo.split(", ")[1]
    # Get Python syntax error
    #
    synerror = traceback.format_exc().splitlines()[-1]
    return line, __file__, synerror
893028
def get_stack_frames(error_stack: bool = True) -> list:
    

    cauldron_path = environ.paths.package()
    resources_path = environ.paths.resources()
    frames = (
        list(traceback.extract_tb(sys.exc_info()[-1]))
        if error_stack else
        traceback.extract_stack()
    ).copy()

    def is_cauldron_code(test_filename: str) -> bool:
        if not test_filename or not test_filename.startswith(cauldron_path):
            return False

        if test_filename.startswith(resources_path):
            return False

        return True

    while len(frames) > 1 and is_cauldron_code(frames[0].filename):
        frames.pop(0)

    return frames
259587
def from_traceback(cls, tb):
        """"""
        stack_trace = cls(
            stack_trace_hash_id=generate_hash_id_from_traceback(tb)
        )
        # use the add_stack_frame so that json formatting is applied
        for tb_frame_info in traceback.extract_tb(tb):
            filename, line_num, fn_name, _ = tb_frame_info
            stack_trace.add_stack_frame(
                StackFrame(
                    func_name=fn_name,
                    original_func_name=fn_name,
                    file_name=filename,
                    line_num=line_num,
                    col_num=0,  # I don't think this is available in python
                    load_module=filename,
                    build_id=BUILD_ID,
                    source_version=SOURCE_VERSION
                )
            )
        return stack_trace
138728
def iter_traceback_frames(tb):
    
    while tb:
        # support for __traceback_hide__ which is used by a few libraries
        # to hide internal frames.
        frame = tb.tb_frame
        f_locals = getattr(frame, "f_locals", {})
        if not _getitem_from_frame(f_locals, "__traceback_hide__"):
            yield frame, getattr(tb, "tb_lineno", None)
        tb = tb.tb_next
369024
def extract_locals(trcback):
    

    output = []
    stack = extract_stack(get_inner_most_frame(trcback))
    for frame, file_name, line_number, name, context, index in stack:
        args_names, nameless, keyword = extract_arguments(frame)
        arguments, nameless_args, keyword_args, locals = OrderedDict(), [], {}, {}
        for key, data in frame.f_locals.iteritems():
            if key == nameless:
                nameless_args = map(repr, frame.f_locals.get(nameless, ()))
            elif key == keyword:
                keyword_args = dict((arg, repr(value)) for arg, value in frame.f_locals.get(keyword, {}).iteritems())
            elif key in args_names:
                arguments[key] = repr(data)
            else:
                locals[key] = repr(data)
        output.append(((name, file_name, line_number), (arguments, nameless_args, keyword_args, locals)))
    return output
1076319
def print_detailed_traceback(self, space=None, file=None):
        """"""
        if file is None:
            file = sys.stderr
        f = io.StringIO()
        for i in range(len(self.debug_excs)-1, -1, -1):
            print >> f, "Traceback (interpreter-level):"
            traceback.print_tb(self.debug_excs[i][2], file=f)
        f.seek(0)
        debug_print(''.join(['|| ' + line for line in f.readlines()]), file)
        if self.debug_excs:
            from pypy.tool import tb_server
            tb_server.publish_exc(self.debug_excs[-1])
        self.print_app_tb_only(file)
        print >> file, '(application-level)', self.errorstr(space)
        if AUTO_DEBUG:
            debug.fire(self)
1341656
def clean_traceback(tb):
    ''''''
    prefix = __file__[:__file__.find("feat/common/error.py")]
    regex = re.compile("(\s*File\s*\")(%s)([a-zA-Z-_\. \\/]*)(\".*)"
                       % prefix.replace("\\", "\\\\"))

    def cleanup(line):
        m = regex.match(line)
        if m:
            return m.group(1) + ".../" + m.group(3) + m.group(4)
        else:
            return line

    return '\n'.join(map(cleanup, tb.split('\n')))
1092936
def get_trace(self, frame, tb):
        """"""
        import linecache
        frames = []
        stack, _ = self.get_stack(frame, tb)
        current = 0

        for i, (stack_frame, lno) in enumerate(stack):
            code = stack_frame.f_code
            filename = code.co_filename or '<unspecified>'
            line = None
            if filename[0] == '<' and filename[-1] == '>':
                line = get_source_from_byte_code(code)
                fn = filename
            else:
                fn = os.path.abspath(filename)
            if not line:
                linecache.checkcache(filename)
                line = linecache.getline(filename, lno, stack_frame.f_globals)
                if not line:
                    line = self.compile_cache.get(id(code), '')
                line = to_unicode_string(line, filename)
                line = line and line.strip()
            startlnos = dis.findlinestarts(code)
            lastlineno = list(startlnos)[-1][1]
            if frame == stack_frame:
                current = i
            frames.append({
                'file': fn,
                'function': code.co_name,
                'flno': code.co_firstlineno,
                'llno': lastlineno,
                'lno': lno,
                'code': line,
                'level': i,
                'current': frame == stack_frame
            })

        # While in exception always put the context to the top
        return stack, frames, current
752834
def generate_plaintext_traceback(self):
        """"""
        yield text_('Traceback (most recent call last):')
        for frame in self.frames:
            yield text_('  File "%s", line %s, in %s' % (
                frame.filename,
                frame.lineno,
                frame.function_name
                ))
            yield text_('    ' + frame.current_line.strip())
        yield text_(self.exception)
211499
def excinfo(e):
    '''
    
    '''
    tb = sys.exc_info()[2]
    path, line, name, sorc = traceback.extract_tb(tb)[-1]
    ret = {
        'err': e.__class__.__name__,
        'errmsg': str(e),
        'errfile': path,
        'errline': line,
    }

    if isinstance(e, s_exc.SynErr):
        ret['errinfo'] = e.errinfo

    return ret
1186149
def showtraceback(self, *args, **kwargs):
        
        try:
            type, value, tb = sys.exc_info()
            sys.last_type = type
            sys.last_value = value
            sys.last_traceback = tb
            tblist = traceback.extract_tb(tb)
            del tblist[:1]
            list = traceback.format_list(tblist)
            if list:
                list.insert(0, "Traceback (most recent call last):\n")
            list[len(list):] = traceback.format_exception_only(type, value)
        finally:
            tblist = tb = None
        map(self.write, list)