Prints the traceback of all threads.

    :param set[int]|list[int]|None exclude_thread_ids: threads to exclude
    :param io.TextIOBase|io.StringIO file: output stream
971479
def dump_all_thread_tracebacks(exclude_thread_ids=None, file=None):
    
    if exclude_thread_ids is None:
        exclude_thread_ids = []
    if not file:
        file = sys.stdout
    import threading

    if hasattr(sys, "_current_frames"):
        print("", file=file)
        threads = {t.ident: t for t in threading.enumerate()}
        # noinspection PyProtectedMember
        for tid, stack in sys._current_frames().items():
            if tid in exclude_thread_ids:
                continue
            # This is a bug in earlier Python versions.
            # http://bugs.python.org/issue17094
            # Note that this leaves out all threads not created via the threading module.
            if tid not in threads:
                continue
            tags = []
            thread = threads.get(tid)
            if thread:
                assert isinstance(thread, threading.Thread)
                if thread is threading.currentThread():
                    tags += ["current"]
                # noinspection PyProtectedMember,PyUnresolvedReferences
                if isinstance(thread, threading._MainThread):
                    tags += ["main"]
                tags += [str(thread)]
            else:
                tags += ["unknown with id %i" % tid]
            print("Thread %s:" % ", ".join(tags), file=file)
            print_tb(stack, file=file)
            print("", file=file)
        print("That were all threads.", file=file)
    else:
        print("Does not have sys._current_frames, cannot get thread tracebacks.", file=file)
794643
def failure_format_traceback(self, fail):
        
        try:
            f = six.StringIO()
            traceback.print_exception(
                fail._type,
                fail.value,
                fail._traceback,
                file=f,
            )
            return f.getvalue()
        except Exception:
            return u"Failed to format failure traceback for '{0}'".format(fail)
709326
def threads_bt(self):
        """"""
        import threading
        import traceback

        threads = {}
        for thread in threading.enumerate():
            frames = sys._current_frames().get(thread.ident)
            if frames:
                stack = traceback.format_stack(frames)
            else:
                stack = []
            threads[thread] = "".join(stack)
        return flask.render_template("gourde/threads.html", threads=threads)
1173957
def print_traceback(with_colors=True):
    
    #traceback.print_tb()
    import traceback
    stack = traceback.extract_stack()
    stack_lines = traceback.format_list(stack)
    tbtext = ''.join(stack_lines)
    if with_colors:
        try:
            from pygments import highlight
            from pygments.lexers import get_lexer_by_name
            from pygments.formatters import TerminalFormatter
            lexer = get_lexer_by_name('pytb', stripall=True)
            formatter = TerminalFormatter(bg='dark')
            formatted_text = highlight(tbtext, lexer, formatter)
            print(formatted_text)
        except Exception:
            print(tbtext)
    else:
        print(tbtext)
453735
def threads_list(io_handler, max_depth=1):
        
        # Normalize maximum depth
        try:
            max_depth = int(max_depth)
            if max_depth < 1:
                max_depth = None
        except (ValueError, TypeError):
            max_depth = None

        # pylint: disable=W0212
        try:
            # Extract frames
            frames = sys._current_frames()

            # Get the thread ID -> Thread mapping
            names = threading._active.copy()
        except AttributeError:
            io_handler.write_line("sys._current_frames() is not available.")
            return

        # Sort by thread ID
        thread_ids = sorted(frames.keys())
        lines = []
        for thread_id in thread_ids:
            # Get the corresponding stack
            stack = frames[thread_id]

            # Try to get the thread name
            try:
                name = names[thread_id].name
            except KeyError:
                name = "<unknown>"

            # Construct the code position
            lines.append("Thread ID: {0} - Name: {1}".format(thread_id, name))
            lines.append("Stack Trace:")

            trace_lines = []
            depth = 0
            frame = stack
            while frame is not None and (
                max_depth is None or depth < max_depth
            ):
                # Store the line information
                trace_lines.append(format_frame_info(frame))

                # Previous frame...
                frame = frame.f_back
                depth += 1

            # Reverse the lines
            trace_lines.reverse()

            # Add them to the printed lines
            lines.extend(trace_lines)
            lines.append("")

        lines.append("")

        # Sort the lines
        io_handler.write("\n".join(lines))
254430
def get_traceback_stxt():
        
        #/
        exc_cls, exc_obj, tb_obj = sys.exc_info()
        
        #/
        txt_s = traceback.format_exception(exc_cls, exc_obj, tb_obj)
    
        #/
        res = ''.join(txt_s)
    
        return res
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
949033
def dump_threads(stream=None):
    '''
    
    '''
    if stream is None:
        stream = sys.stderr
    thread_id_to_name = {}
    try:
        for t in threading.enumerate():
            thread_id_to_name[t.ident] = '%s  (daemon: %s, pydevd thread: %s)' % (
                t.name, t.daemon, getattr(t, 'is_pydev_daemon_thread', False))
    except:
        pass

    from _pydevd_bundle.pydevd_additional_thread_info_regular import _current_frames

    stream.write('===============================================================================\n')
    stream.write('Threads running\n')
    stream.write('================================= Thread Dump =================================\n')
    stream.flush()

    for thread_id, stack in _current_frames().items():
        stream.write('\n-------------------------------------------------------------------------------\n')
        stream.write(" Thread %s" % thread_id_to_name.get(thread_id, thread_id))
        stream.write('\n\n')

        for i, (filename, lineno, name, line) in enumerate(traceback.extract_stack(stack)):

            stream.write(' File "%s", line %d, in %s\n' % (filename, lineno, name))
            if line:
                stream.write("   %s\n" % (line.strip()))

            if i == 0 and 'self' in stack.f_locals:
                stream.write('   self: ')
                try:
                    stream.write(str(stack.f_locals['self']))
                except:
                    stream.write('Unable to get str of: %s' % (type(stack.f_locals['self']),))
                stream.write('\n')
        stream.flush()

    stream.write('\n=============================== END Thread Dump ===============================')
    stream.flush()
436067
def ListThreads(self):
    
    if self.inferior.is_running:
      return self.inferior.threads
    logging.error('Not attached to any process.')
    return []
828127
def dump_stacktraces():
    
    lines = []
    for thread_id, stack in sys._current_frames().items():  # pylint: disable=W0212
        lines.append("\n######### ProcessID=%s, ThreadID=%s #########" % (
            os.getpid(), thread_id
        ))
        for filename, lineno, name, line in traceback.extract_stack(stack):
            lines.append('File: "%s", line %d, in %s' % (filename, lineno, name))
            if line:
                lines.append("  %s" % (line.strip()))
    lines.append("#############################################\n\n")

    print('\n'.join(lines), file=sys.stderr if _MANHOLE.redirect_stderr else sys.stdout)
238315
def start_tracing_process(self, pid):
        
        for thread in self.system.get_process(pid).iter_threads():
            self.__start_tracing(thread)
1124740
def output_traceback(ex):
    """"""
    # Dump full traceback to console.
    output = "".join(traceback.format_exc()).strip()
    for line in output.split('\n'):
        logging.error(line)
    trace_obj = traceback.extract_tb(ex.__traceback__)[-1]
    trace = [basename(trace_obj[0]), trace_obj[1]]
    name = type(ex).__name__
    output = str(ex).replace('\n', ' ')
    msg = "%s in %s on line %s: %s" % (name, trace[0], trace[1], output)
    return (msg, output)
196987
def _asynciostacks(*args, **kwargs):  # pragma: no cover
    '''
    
    '''
    print(80 * '*')
    print('Asyncio tasks stacks:')
    tasks = asyncio.all_tasks(_glob_loop)
    for task in tasks:
        task.print_stack()
    print(80 * '*')
    print('Faulthandler stack frames per thread:')
    faulthandler.dump_traceback()
    print(80 * '*')
403284
def traceback(cls, error=None, debug=True, trace=True):
        
        # TODO: if debug:
        Error.msg(error=error, debug=debug, trace=trace)
573515
def dump_tracing_state(self, context):
        
        _logger.x_debug("Dumping all threads Tracing state: (%s)" % context)
        _logger.x_debug("    self.tracing_enabled=%s" % self.tracing_enabled)
        _logger.x_debug("    self.execution_started=%s" % self.execution_started)
        _logger.x_debug("    self.status=%s" % self.status)
        _logger.x_debug("    self.frame_beginning=%s" % self.frame_beginning)
        _logger.x_debug("    self.debugger_thread_ident=%s" % self.debugger_thread_ident)
        if False:
            for thr in threading.enumerate():
                is_current_thread = thr.ident == threading.current_thread().ident
                _logger.x_debug("    Thread: %s, %s %s" % (thr.name, thr.ident, "<= Current*" if is_current_thread else ''))
                a_frame = sys._current_frames()[thr.ident]
                while a_frame:
                    flags = []
                    if a_frame == self.frame_beginning:
                        flags.append("beginning")
                    if a_frame == inspect.currentframe():
                        flags.append("current")
                    if flags:
                        flags_str = "**"+",".join(flags)
                    else:
                        flags_str = ""
                    _logger.x_debug("        => %s, %s:%s(%s) | %s %s" % (a_frame, 
                                                                          a_frame.f_code.co_filename, 
                                                                          a_frame.f_lineno,
                                                                          a_frame.f_code.co_name, 
                                                                          a_frame.f_trace,
                                                                          flags_str))
                    a_frame = a_frame.f_back
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)
462139
def _printTraceback(self, test, err):
        
        # Don't bind third item to a local var; that can create
        # circular refs which are expensive to collect. See the
        # sys.exc_info() docs.
        exception_type, exception_value = err[:2]
        # TODO: In Python 3, the traceback is attached to the exception
        # instance through the __traceback__ attribute. If the instance
        # is saved in a local variable that persists outside the except
        # block, the traceback will create a reference cycle with the
        # current frame and its dictionary of local variables. This will
        # delay reclaiming dead resources until the next cyclic garbage
        # collection pass.

        extracted_tb = extract_relevant_tb(
            err[2],
            exception_type,
            exception_type is test.failureException)
        test_frame_index = index_of_test_frame(
            extracted_tb,
            exception_type,
            exception_value,
            test)
        if test_frame_index:
            # We have a good guess at which frame is the test, so
            # trim everything until that. We don't care to see test
            # framework frames.
            extracted_tb = extracted_tb[test_frame_index:]

        with self.bar.dodging():
            self.stream.write(''.join(
                format_traceback(
                    extracted_tb,
                    exception_type,
                    exception_value,
                    self._cwd,
                    self._term,
                    self._options.function_color,
                    self._options.dim_color,
                    self._options.editor,
                    self._options.editor_shortcut_template)))