Make a StringIO of the usual traceback information, followed by a
  listing of all the local variables in each frame.
438835
def log_fault_info_str (exc_info, message = "", level = logging.CRITICAL,
                        traceback = False):
  
  tb = sys.exc_info ()[2]
  stack = _get_stack (tb)
  rc = StringIO ()
  rc.write ("%s: FAULT: %s%s(%s): %s\n"
            % (logging.getLevelName (level),
               ("%s -- " % message) if message else "",
               tb.tb_frame.f_code.co_filename,
               tb.tb_lineno,
               repr (exc_info[1])))
  if traceback:
    for line in _generate_stackdump (stack):
      rc.write ("%s\n" % line)
  return rc.getvalue ()
209346
def showtraceback(self, *args, **kwargs):
        """"""
        # Override for avoid using sys.excepthook PY-12600
        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]
            lines = traceback.format_list(tblist)
            if lines:
                lines.insert(0, "Traceback (most recent call last):\n")
            lines.extend(traceback.format_exception_only(type, value))
        finally:
            tblist = tb = None
        sys.stderr.write(''.join(lines))
1109454
private void visitImplicitFirstFrame() {
        // There can be at most descriptor.length() + 1 locals
        int frameIndex = startFrame(0, descriptor.length() + 1, 0);
        if ((access & Opcodes.ACC_STATIC) == 0) {
            if ((access & ACC_CONSTRUCTOR) == 0) {
                frame[frameIndex++] = Frame.OBJECT | cw.addType(cw.thisName);
            } else {
                frame[frameIndex++] = Frame.UNINITIALIZED_THIS;
            }
        }
        int i = 1;
        loop: while (true) {
            int j = i;
            switch (descriptor.charAt(i++)) {
            case 'Z':
            case 'C':
            case 'B':
            case 'S':
            case 'I':
                frame[frameIndex++] = Frame.INTEGER;
                break;
            case 'F':
                frame[frameIndex++] = Frame.FLOAT;
                break;
            case 'J':
                frame[frameIndex++] = Frame.LONG;
                break;
            case 'D':
                frame[frameIndex++] = Frame.DOUBLE;
                break;
            case '[':
                while (descriptor.charAt(i) == '[') {
                    ++i;
                }
                if (descriptor.charAt(i) == 'L') {
                    ++i;
                    while (descriptor.charAt(i) != ';') {
                        ++i;
                    }
                }
                frame[frameIndex++] = Frame.type(cw, descriptor.substring(j, ++i));
                break;
            case 'L':
                while (descriptor.charAt(i) != ';') {
                    ++i;
                }
                frame[frameIndex++] = Frame.OBJECT
                        | cw.addType(descriptor.substring(j + 1, i++));
                break;
            default:
                break loop;
            }
        }
        frame[1] = frameIndex - 3;
        endFrame();
    }
1333343
def render_summary(self, app, include_title=True):
        """"""
        title = ''
        frames = []
        classes = ['traceback']
        if not self.frames:
            classes.append('noframe-traceback')

        if include_title:
            if self.is_syntax_error:
                title = text_('Syntax Error')
            else:
                title = text_('Traceback <small>(most recent call last)'
                              '</small>')

        for frame in self.frames:
            txt = frame.info
            if not txt:
                txt = text_(' title="%s"' % escape(frame.info))
            if not txt:
                txt = text_('')
            frames.append(
                text_('<li%s>%s') % (txt, frame.render()))

        if self.is_syntax_error:
            description_wrapper = text_('<pre class=syntaxerror>%s</pre>')
        else:
            description_wrapper = text_('<blockquote>%s</blockquote>')
        vars = {
            'classes': text_(' '.join(classes)),
            'title': title and text_('<h3 class="traceback">%s</h3>'
                                     % title) or text_(''),
            'frames': text_('\n'.join(frames)),
            'description': description_wrapper % escape(self.exception),
        }
        return render('exception_summary.jinja2', app, vars)
597836
def render_summary(self, include_title=True, request=None):
        """"""
        title = ''
        frames = []
        classes = ['traceback']
        if not self.frames:
            classes.append('noframe-traceback')

        if include_title:
            if self.is_syntax_error:
                title = text_('Syntax Error')
            else:
                title = text_('Traceback <small>(most recent call last)'
                              '</small>')

        for frame in self.frames:
            frames.append(
                text_('<li%s>%s') % (
                    frame.info and text_(' title="%s"' % escape(frame.info)) or
                    text_(''),
                    frame.render()
                ))

        if self.is_syntax_error:
            description_wrapper = text_('<pre class=syntaxerror>%s</pre>')
        else:
            description_wrapper = text_('<blockquote>%s</blockquote>')

        vars = {
            'classes': text_(' '.join(classes)),
            'title': title and text_('<h3 class="traceback">%s</h3>'
                                     % title) or text_(''),
            'frames': text_('\n'.join(frames)),
            'description': description_wrapper % escape(self.exception),
        }
        app = request.app
        template = app.ps.jinja2.env.get_template('debugtoolbar/exception_summary.html')
        return template.render(app=app, request=request, **vars)
629017
def trace():
    
    import traceback, inspect, sys
    tb = sys.exc_info()[2]
    tbinfo = traceback.format_tb(tb)[0]
    filename = inspect.getfile(inspect.currentframe())
    # script name + line number
    line = tbinfo.split(", ")[1]
    # Get Python syntax error
    #
    synerror = traceback.format_exc().splitlines()[-1]
    return line, filename, synerror
1164486
def debug(s, *args):
    """"""
    # Get the path name and line number of the function which called us.
    previous_frame = inspect.currentframe().f_back
    try:
        pathname, lineno, _, _, _ = inspect.getframeinfo(previous_frame)
        # if path is in cwd, simplify it
        cwd = os.path.abspath(os.getcwd())
        pathname = os.path.abspath(pathname)
        if os.path.commonprefix([cwd, pathname]) == cwd:
            pathname = os.path.relpath(pathname, cwd)
    except Exception:  # pylint: disable=broad-except
        pathname = '<UNKNOWN-FILE>.py'
        lineno = 0
    if _FORMATTER: # log could have not been initialized.
        _FORMATTER.pathname = pathname
        _FORMATTER.lineno = lineno
    logger = logging.getLogger(__package__)
    logger.debug(s.format(*args))
89336
def str_traceback(error, tb):
    
    if not isinstance(tb, types.TracebackType):
        return tb

    return ''.join(traceback.format_exception(error.__class__, error, tb))
348817
def format_frame_info(frame):
    
    # Same as in traceback.extract_stack
    line_no = frame.f_lineno
    code = frame.f_code
    filename = code.co_filename
    method_name = code.co_name
    linecache.checkcache(filename)

    try:
        # Try to get the type of the calling object
        instance = frame.f_locals["self"]
        method_name = "{0}::{1}".format(type(instance).__name__, method_name)
    except KeyError:
        # Not called from a bound method
        pass

    # File & line
    output_lines = [
        '  File "{0}", line {1}, in {2}'.format(filename, line_no, method_name)
    ]

    # Arguments
    if frame.f_locals:
        # Pypy keeps f_locals as an empty dictionary
        arg_info = inspect.getargvalues(frame)
        for name in arg_info.args:
            try:
                output_lines.append(
                    "    - {0:s} = {1}".format(name, repr(frame.f_locals[name]))
                )
            except TypeError:
                # Happens in dict/list-comprehensions in Python 2.x
                name = name[0]
                output_lines.append(
                    "    - {0:s} = {1}".format(name, repr(frame.f_locals[name]))
                )

        if arg_info.varargs:
            output_lines.append(
                "    - *{0:s} = {1}".format(
                    arg_info.varargs, frame.f_locals[arg_info.varargs]
                )
            )

        if arg_info.keywords:
            output_lines.append(
                "    - **{0:s} = {1}".format(
                    arg_info.keywords, frame.f_locals[arg_info.keywords]
                )
            )

    # Line block
    lines = _extract_lines(filename, frame.f_globals, line_no, 3)
    if lines:
        output_lines.append("")
        prefix = "      "
        output_lines.append(
            "{0}{1}".format(prefix, "\n{0}".format(prefix).join(lines))
        )
    return "\n".join(output_lines)
794093
def _trace (frame, event, arg):
    """"""
    if event in ('call', 'c_call'):
        _trace_line(frame, event, arg)
    elif event in ('return', 'c_return'):
        _trace_line(frame, event, arg)
        print("  return:", arg)
    #elif event in ('exception', 'c_exception'):
    #    _trace_line(frame, event, arg)
    return _trace
1181297
def format_exception(self):
        
        import traceback
        frames = self.get_traceback_frames()
        tb = [(f['filename'], f['lineno'], f['function'], f['context_line']) for f in frames]
        list = ['Traceback (most recent call last):\n']
        list += traceback.format_list(tb)
        list += traceback.format_exception_only(self.exc_type, self.exc_value)
        return list
486101
def debug(trace=True, backtrace=1, other=None, output=sys.stderr):
    """"""
    from pprint import pprint
    import traceback
    def debugdeco(func):
        def tracer(frame, event, arg):
            print>>output, '--- Tracer: %s, %r' % (event, arg)
            traceback.print_stack(frame, 1, output)
            return tracer
        def wrapped(*a, **k):
            print>>output
            print>>output, '--- Calling %s.%s with:' % (
                getattr(func, '__module__', ''),
                func.__name__
            )
            for i in enumerate(a):
                print>>output, '    | %s: %s' % i
            print>>output, '    | ',
            pprint(k, output)
            print>>output, '    From:'
            for i in traceback.format_stack(sys._getframe(1), backtrace):
                print>>output, i,
            if other:
                print>>output, '---      [ %r ]' % (other(func,a,k))
            if trace: sys.settrace(tracer)
            ret = func(*a, **k)
            if trace: sys.settrace(None)
            #~ a = list(a)
            print>>output, '--- %s.%s returned: %r' % (
                getattr(func, '__module__', ''),
                func.__name__,
                #~ ret not in a and ret or "ARG%s"%a.index(ret)
                ret
            )
            return ret
        return wrapped
    return debugdeco
92330
def frame_info(self):
        """"""
        if not self._logger.isEnabledFor(logging.DEBUG):
            return ''
        f = sys._getframe(3)
        fname = os.path.split(f.f_code.co_filename)[1]
        return '{}:{}'.format(fname, f.f_lineno)
505591
def dump_frames(self, frame):
        
        current_thread = threading.currentThread()
        frames = []
        frame_browser = frame
        
        # Browse the frame chain as far as we can
        _logger.f_debug("dump_frames(), frame analysis:")
        spacer = ""
        while hasattr(frame_browser, 'f_back') and frame_browser.f_back != self.frame_beginning:
            spacer += "="
            _logger.f_debug("%s>frame = %s, frame.f_code = %s, frame.f_back = %s, "
                            "self.frame_beginning = %s",
                            spacer,
                            hex(id(frame_browser)),
                            frame_browser.f_code,
                            hex(id(frame_browser.f_back)),
                            hex(id(self.frame_beginning)))

            # At root frame, globals == locals so we dump only globals
            if hasattr(frame_browser.f_back, 'f_back')\
                    and frame_browser.f_back.f_back != self.frame_beginning:
                locals_vars_list = self.extract_object_properties(frame_browser.f_locals,
                                                                  limit_size=True)
            else:
                locals_vars_list = []
                                
            globals_vars_list = self.extract_object_properties(frame_browser.f_globals,
                                                               limit_size=True)
            # normalize path sent to debugging client
            file_path = self.normalize_path_out(frame_browser.f_code.co_filename)

            frame_name = "%s() [%s]" % (frame_browser.f_code.co_name, current_thread.name,)
            remote_frame = {
                'id': id(frame_browser),
                'name': frame_name,
                'line_number': frame_browser.f_lineno,  # Warning 1 based
                'file_path': file_path,
                'f_locals': locals_vars_list + globals_vars_list,
                'thread': current_thread.ident,
                'thread_name': current_thread.name
            }
            frames.append(remote_frame)
            frame_browser = frame_browser.f_back
        return frames
907950
def get_traceback_frames(self):
        """"""
        frames = []
        tb = self.tb
        while tb is not None:
            # Support for __traceback_hide__ which is used by a few libraries
            # to hide internal frames.
            if tb.tb_frame.f_locals.get('__traceback_hide__'):
                tb = tb.tb_next
                continue
            filename = tb.tb_frame.f_code.co_filename
            function = tb.tb_frame.f_code.co_name
            lineno = tb.tb_lineno - 1
            loader = tb.tb_frame.f_globals.get('__loader__')
            module_name = tb.tb_frame.f_globals.get('__name__') or ''
            pre_context_lineno, pre_context, context_line, post_context = self._get_lines_from_file(
                filename, lineno, 7, loader, module_name,
            )
            if pre_context_lineno is not None:
                frames.append({
                    'tb': tb,
                    'type': 'django' if module_name.startswith('django.') else 'user',
                    'filename': filename,
                    'function': function,
                    'lineno': lineno + 1,
                    'vars': list(six.iteritems(tb.tb_frame.f_locals)),
                    'id': id(tb),
                    'pre_context': pre_context,
                    'context_line': context_line,
                    'post_context': post_context,
                    'pre_context_lineno': pre_context_lineno + 1,
                })
            tb = tb.tb_next

        return frames
339768
def getouterframes(frame, context=1):
    """"""
    framelist = []
    while frame:
        framelist.append((frame,) + getframeinfo(frame, context))
        frame = frame.f_back
    return framelist
590479
def _methodInTraceback(self, name, traceback):
    '''
    
    '''
    foundMethod = False
    for frame in self._frames(traceback):
      this = frame.f_locals.get('self')
      if this is self and frame.f_code.co_name == name:
        foundMethod = True
        break
    return foundMethod