Make tracebacks after exceptions colored, verbose, and/or call pdb
    (python cmd line debugger) at the place where the exception occurs
432051
def color_exepthook(pdb=0, mode=2):
    

    modus = ['Plain', 'Context', 'Verbose'][mode] # select the mode

    sys.excepthook = ultratb.FormattedTB(mode=modus,
                                    color_scheme='Linux', call_pdb=pdb)
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
709044
def do_debug(self, arg):
        
        self.settrace(False)
        globals = self.curframe.f_globals
        locals = self.get_locals(self.curframe)
        p = Pdb(self.completekey, self.stdin, self.stdout, debug=True)
        p.prompt = "(%s) " % self.prompt.strip()
        self.message("ENTERING RECURSIVE DEBUGGER")
        sys.call_tracing(p.run, (arg, globals, locals))
        self.message("LEAVING RECURSIVE DEBUGGER")
        self.settrace(True)
        self.lastcmd = p.lastcmd
792881
def exception_occurred(self, text, is_traceback):
        
        # Skip errors without traceback or dismiss
        if (not is_traceback and self.error_dlg is None) or self.dismiss_error:
            return

        if CONF.get('main', 'show_internal_errors'):
            if self.error_dlg is None:
                self.error_dlg = SpyderErrorDialog(self)
                self.error_dlg.close_btn.clicked.connect(self.close_error_dlg)
                self.error_dlg.rejected.connect(self.remove_error_dlg)
                self.error_dlg.details.go_to_error.connect(self.go_to_error)
                self.error_dlg.show()
            self.error_dlg.append_traceback(text)
        elif DEV or get_debug_level():
            self.dockwidget.show()
            self.dockwidget.raise_()
615986
def trace_method(method):
    

    def wrapper(*args, **kwargs):
        try:
            method(*args, **kwargs)
        except Exception:
            args[0].print_exception("A worker thread crashed:\n" + traceback.format_exc())

    return wrapper
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)
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)
198961
def start_debugging():
    
    exc_type, exc_value, exc_tb = sys.exc_info()

    # If the exception has been annotated to be re-raised, raise the exception
    if hasattr(exc_value, '_ipdbugger_let_raise'):
        raise_(*sys.exc_info())

    print()
    for line in traceback.format_exception(exc_type, exc_value, exc_tb):
        print(colored(line, 'red'), end=' ')

    # Get the frame with the error.
    test_frame = sys._getframe(-1).f_back

    from ipdb.__main__ import wrap_sys_excepthook
    wrap_sys_excepthook()
    IPDBugger(exc_info=sys.exc_info()).set_trace(test_frame)
643600
def trace_debug_dispatch(self, frame, event, arg):
        """"""
        trace_log.info(
            'Frame:%s. Event: %s. Arg: %r' % (pretty_frame(frame), event, arg)
        )
        trace_log.debug(
            'state %r breaks ? %s stops ? %s' % (
                self.state, self.breaks(frame, no_remove=True),
                self.state.stops(frame, event)
            )
        )
        if event == 'return':
            trace_log.debug(
                'Return: frame: %s, state: %s, state.f_back: %s' % (
                    pretty_frame(frame), pretty_frame(self.state.frame),
                    pretty_frame(self.state.frame.f_back)
                )
            )
        if self.trace_dispatch(frame, event, arg):
            return self.trace_debug_dispatch
        trace_log.debug("No trace %s" % pretty_frame(frame))
420007
def pdb_run(func: Callable, *args: Any, **kwargs: Any) -> None:
    
    # noinspection PyBroadException
    try:
        func(*args, **kwargs)
    except:  # nopep8
        type_, value, tb = sys.exc_info()
        traceback.print_exc()
        pdb.post_mortem(tb)
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))
816866
def setup_exceptions():
    
    # first set up the variables needed by the _excepthook function
    global _print_traceback, _drill
    local_print_traceback = os.getenv("PYLOGCONF_PRINT_TRACEBACK")
    if local_print_traceback is not None:
        _print_traceback = _str2bool(local_print_traceback)
    local_drill = os.getenv("PYLOGCONF_DRILL")
    if local_drill is not None:
        _drill = _str2bool(local_drill)
    # now that everything is ready attach the hook
    sys.excepthook = _excepthook
395108
def excepthook(exc_type, exc_value, tracebackobj):
    
    separator = "-" * 80
    notice = "The following error was triggered:"

    now = datetime.now().strftime("%Y-%m-%d, %H:%M:%S")

    info = StringIO()
    traceback.print_tb(tracebackobj, None, info)
    info.seek(0)
    info = info.read()

    errmsg = f"{exc_type}\t \n{exc_value}"
    sections = [now, separator, errmsg, separator, info]
    msg = "\n".join(sections)

    print(''.join(traceback.format_tb(tracebackobj)))
    print('{0}: {1}'.format(exc_type, exc_value))

    QtWidgets.QMessageBox.warning(None, notice, traceback.format_exc())
1115484
def ddebug(msg, err=None):  # pragma: no cover
    
    import os
    if err:
        err = ''.join(traceback.format_exception(*err))
    else:
        err = ''
    sys.__stdout__.write("({}) {} {}".format(os.getpid(), msg, err)+'\n')
    sys.__stdout__.flush()
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')))
682371
def print_application_traceback(self, space, file=None):
        ""
        if file is None:
            file = sys.stderr
        self.print_app_tb_only(file)
        print >> file, self.errorstr(space)
90569
def _exception(etype, eval_, etrace):
        
        if hasattr(sys, 'ps1') or not sys.stderr.isatty():
            # we are in interactive mode or we don't have a tty-like
            # device, so we call the default hook
            sys.__excepthook__(etype, eval_, etrace)
        else:
            # we are NOT in interactive mode, print the exception...
            traceback.print_exception(etype, eval_, etrace, limit=2,
                                      file=sys.stdout)
            six.print_()
            # ...then start the debugger in post-mortem mode.
            pdb.pm()