Python traceback.format_stack() Examples

The following are 30 code examples of traceback.format_stack(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module traceback , or try the search function .
Example #1
Source File: output.py    From stem with GNU Lesser General Public License v3.0 7 votes vote down vote up
def thread_stacktraces():
  """
  Provides a dump of the stacktrace information for all active threads.

  :returns: **dict** that maps thread names to their stacktrace
  """

  stacktraces = {}

  for thread in threading.enumerate():
    frame = sys._current_frames().get(thread.ident, None)

    if frame:
      stacktraces[thread.name] = ''.join(traceback.format_stack(frame))
    else:
      stacktraces[thread.name] = 'No traceback available'

  return stacktraces 
Example #2
Source File: pool.py    From jbox with MIT License 6 votes vote down vote up
def _do_get(self):
        if self._checked_out:
            if self._checkout_traceback:
                suffix = ' at:\n%s' % ''.join(
                    chop_traceback(self._checkout_traceback))
            else:
                suffix = ''
            raise AssertionError("connection is already checked out" + suffix)

        if not self._conn:
            self._conn = self._create_connection()

        self._checked_out = True
        if self._store_traceback:
            self._checkout_traceback = traceback.format_stack()
        return self._conn 
Example #3
Source File: config.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def log(msg, msgx='', level=logging.INFO, need_tb=False):
    """
    Logging in UCC Config Module.
    :param msg: message content
    :param msgx: detail info.
    :param level: logging level
    :param need_tb: if need logging traceback
    :return:
    """
    global LOGGING_STOPPED
    if LOGGING_STOPPED:
        return

    msgx = ' - ' + msgx if msgx else ''
    content = 'UCC Config Module: %s%s' % (msg, msgx)
    if need_tb:
        stack = ''.join(traceback.format_stack())
        content = '%s\r\n%s' % (content, stack)
    stulog.logger.log(level, content, exc_info=1) 
Example #4
Source File: config.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def log(msg, msgx='', level=logging.INFO, need_tb=False):
    """
    Logging in UCC Config Module.
    :param msg: message content
    :param msgx: detail info.
    :param level: logging level
    :param need_tb: if need logging traceback
    :return:
    """
    global LOGGING_STOPPED
    if LOGGING_STOPPED:
        return

    msgx = ' - ' + msgx if msgx else ''
    content = 'UCC Config Module: %s%s' % (msg, msgx)
    if need_tb:
        stack = ''.join(traceback.format_stack())
        content = '%s\r\n%s' % (content, stack)
    stulog.logger.log(level, content, exc_info=1) 
Example #5
Source File: help_functions.py    From pylane with GNU General Public License v3.0 6 votes vote down vote up
def inspect_threads(thread_names=[]):
    """inspect_threads() -> {thread_name: {"locals": {}, "stack": ""}} : return threads' locals and stack"""
    import threading
    import sys
    import traceback
    pylane_thread_name = "pylane-shell-thread"
    stacks = {}
    frames = sys._current_frames()
    threads = threading.enumerate()
    for thread in threads:
        if thread.name == pylane_thread_name:
            continue
        if thread_names and thread.name not in thread_names:
            continue
        frame = frames.get(thread.ident)
        stack = ''.join(traceback.format_stack(frame)) if frame else ''
        stacks[thread.name] = {
            "locals": frame.f_locals,
            "stack": stack
        }
    return stacks 
Example #6
Source File: __init__.py    From universe with MIT License 6 votes vote down vote up
def format_error(e):
    # errback automatically wraps everything in a Twisted Failure
    if isinstance(e, failure.Failure):
        e = e.value

    if isinstance(e, str):
        err_string = e
    elif six.PY2:
        err_string = traceback.format_exc(e).rstrip()
    else:
        err_string = ''.join(traceback.format_exception(type(e), e, e.__traceback__)).rstrip()

    if err_string == 'None':
        # Reasonable heuristic for exceptions that were created by hand
        last = traceback.format_stack()[-2]
        err_string = '{}\n  {}'.format(e, last)
    # Quick and dirty hack for now.
    err_string = err_string.replace('Connection to the other side was lost in a non-clean fashion', 'Connection to the other side was lost in a non-clean fashion (HINT: this generally actually means we got a connection refused error. Check that the remote is actually running.)')
    return error.Error(err_string) 
Example #7
Source File: report.py    From iopipe-python with Apache License 2.0 6 votes vote down vote up
def retain_error(self, error, frame=None):
        """
        Adds details of an error to the report.

        :param error: The error exception to add to the report.
        """
        if frame is None:
            stack = traceback.format_exc()
            self.labels.add("@iopipe/error")
        else:
            stack = "\n".join(traceback.format_stack(frame))
            self.labels.add("@iopipe/timeout")
        details = {
            "name": type(error).__name__,
            "message": "{}".format(error),
            "stack": stack,
        }
        self.report["errors"] = details 
Example #8
Source File: message.py    From qutebrowser with GNU General Public License v3.0 6 votes vote down vote up
def error(message: str, *, stack: str = None, replace: bool = False) -> None:
    """Display an error message.

    Args:
        message: The message to show.
        stack: The stack trace to show (if any).
        replace: Replace existing messages which are still being shown.
    """
    if stack is None:
        stack = ''.join(traceback.format_stack())
        typ = 'error'
    else:
        typ = 'error (from exception)'
    _log_stack(typ, stack)
    log.message.error(message)
    global_bridge.show(usertypes.MessageLevel.error, message, replace) 
Example #9
Source File: mutex.py    From tf-pose with Apache License 2.0 6 votes vote down vote up
def tryLock(self, timeout=None, id=None):
        if timeout is None:
            locked = QtCore.QMutex.tryLock(self)
        else:
            locked = QtCore.QMutex.tryLock(self, timeout)

        if self.debug and locked:
            self.l.lock()
            try:
                if id is None:
                    self.tb.append(''.join(traceback.format_stack()[:-1]))
                else:
                    self.tb.append("  " + str(id))
                #print 'trylock', self, len(self.tb)
            finally:
                self.l.unlock()
        return locked 
Example #10
Source File: defer.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def _startRunCallbacks(self, result):
        if self.called:
            if self._suppressAlreadyCalled:
                self._suppressAlreadyCalled = False
                return
            if self.debug:
                if self._debugInfo is None:
                    self._debugInfo = DebugInfo()
                extra = "\n" + self._debugInfo._getDebugTracebacks()
                raise AlreadyCalledError(extra)
            raise AlreadyCalledError
        if self.debug:
            if self._debugInfo is None:
                self._debugInfo = DebugInfo()
            self._debugInfo.invoker = traceback.format_stack()[:-2]
        self.called = True
        self.result = result
        self._runCallbacks() 
Example #11
Source File: base.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, time, func, args, kw, cancel, reset,
                 seconds=runtimeSeconds):
        """
        @param time: Seconds from the epoch at which to call C{func}.
        @param func: The callable to call.
        @param args: The positional arguments to pass to the callable.
        @param kw: The keyword arguments to pass to the callable.
        @param cancel: A callable which will be called with this
            DelayedCall before cancellation.
        @param reset: A callable which will be called with this
            DelayedCall after changing this DelayedCall's scheduled
            execution time. The callable should adjust any necessary
            scheduling details to ensure this DelayedCall is invoked
            at the new appropriate time.
        @param seconds: If provided, a no-argument callable which will be
            used to determine the current time any time that information is
            needed.
        """
        self.time, self.func, self.args, self.kw = time, func, args, kw
        self.resetter = reset
        self.canceller = cancel
        self.seconds = seconds
        self.cancelled = self.called = 0
        self.delayed_time = 0
        if self.debug:
            self.creator = traceback.format_stack()[:-2] 
Example #12
Source File: utils.py    From jd_analysis with GNU Lesser General Public License v3.0 5 votes vote down vote up
def log(msg, level = logging.DEBUG):
    logging.log(level, msg)
    print('%s [%s], msg:%s' % (datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), level, msg))

    # if level == logging.WARNING or level == logging.ERROR:
    #     for line in traceback.format_stack():
    #         print(line.strip())
    #
    #     for line in traceback.format_stack():
    #         logging.log(level, line.strip())


# 服务器使用,清理端口占用 
Example #13
Source File: defer.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, canceller=None):
        """
        Initialize a L{Deferred}.

        @param canceller: a callable used to stop the pending operation
            scheduled by this L{Deferred} when L{Deferred.cancel} is
            invoked. The canceller will be passed the deferred whose
            cancelation is requested (i.e., self).

            If a canceller is not given, or does not invoke its argument's
            C{callback} or C{errback} method, L{Deferred.cancel} will
            invoke L{Deferred.errback} with a L{CancelledError}.

            Note that if a canceller is not given, C{callback} or
            C{errback} may still be invoked exactly once, even though
            defer.py will have already invoked C{errback}, as described
            above.  This allows clients of code which returns a L{Deferred}
            to cancel it without requiring the L{Deferred} instantiator to
            provide any specific implementation support for cancellation.
            New in 10.1.

        @type canceller: a 1-argument callable which takes a L{Deferred}. The
            return result is ignored.
        """
        self.callbacks = []
        self._canceller = canceller
        if self.debug:
            self._debugInfo = DebugInfo()
            self._debugInfo.creator = traceback.format_stack()[:-1] 
Example #14
Source File: parallel.py    From beat with GNU General Public License v3.0 5 votes vote down vote up
def overseer(timeout):
    """
    Function decorator that raises a TimeoutException exception
    after timeout seconds, if the decorated function did not return.
    """

    def decorate(func):
        def timeout_handler(signum, frame):
            raise TimeoutException(traceback.format_stack())

        @wraps(func)
        def wrapped_f(*args, **kwargs):
            old_handler = signal.signal(signal.SIGALRM, timeout_handler)
            signal.alarm(timeout)

            result = func(*args, **kwargs)

            # Old signal handler is restored
            signal.signal(signal.SIGALRM, old_handler)
            signal.alarm(0)  # Alarm removed
            return result

        wrapped_f.__name__ = func.__name__
        return wrapped_f

    return decorate 
Example #15
Source File: __init__.py    From concurrent-log-handler with Apache License 2.0 5 votes vote down vote up
def _console_log(self, msg, stack=False):
        if not self._debug:
            return
        import threading
        tid = threading.current_thread().name
        pid = os.getpid()
        stack_str = ''
        if stack:
            stack_str = ":\n" + "".join(traceback.format_stack())
        asctime = time.asctime()
        print("[%s %s %s] %s%s" % (tid, pid, asctime, msg, stack_str,)) 
Example #16
Source File: Utils.py    From royal-chaos with MIT License 5 votes vote down vote up
def print_backtrace():
    """ Prints the full trace of the exception."""
     
    import sys
    import traceback
    trace = ""
    exception = ""
    
    exceptionHandling = True
    if(not sys.exc_info()[0] or not sys.exc_info()[1]):
        exceptionHandling = False
        
    if exceptionHandling: 
        exc_list = traceback.format_exception_only (sys.exc_info()[0],sys.exc_info()[1])

        for entry in exc_list:
            exception += entry
    
        tb_list = traceback.format_tb(sys.exc_info()[2])
    else:
        tb_list = traceback.format_stack()
        
    for entry in tb_list:
        trace += entry

    toWrite = "\n%s\n%s" % (exception, trace)
    sys.stderr.write(toWrite)
    return toWrite 
Example #17
Source File: gunicorn_config.py    From notifications-api with MIT License 5 votes vote down vote up
def worker_abort(worker):
    worker.log.info("worker received ABORT {}".format(worker.pid))
    for threadId, stack in sys._current_frames().items():
        worker.log.error(''.join(traceback.format_stack(stack))) 
Example #18
Source File: core.py    From vlcp with Apache License 2.0 5 votes vote down vote up
def _tracesignal(self, signum, frame):
        import traceback
        self.logger.warning('Signal USR1, trace:\n%s', ''.join(traceback.format_stack())) 
Example #19
Source File: wnd_utils.py    From dash-masternode-tool with MIT License 5 votes vote down vote up
def run_thread(parent, worker_fun, worker_fun_args, on_thread_finish=None,
                   on_thread_exception=None, skip_raise_exception=False):
        """
        Run a function inside a thread.
        :param worker_fun: reference to function to be executed inside a thread
        :param worker_fun_args: arguments passed to a thread function
        :param on_thread_finish: function to be called after thread finishes its execution
        :param skip_raise_exception: Exception raised inside the 'worker_fun' will be passed to the calling thread if:
            - on_thread_exception is a valid function (it's exception handler)
            - skip_raise_exception is False
        :return: reference to a thread object
        """

        def on_thread_finished_int(thread_arg, on_thread_finish_arg, skip_raise_exception_arg, on_thread_exception_arg):
            if thread_arg.worker_exception:
                if on_thread_exception_arg:
                    on_thread_exception_arg(thread_arg.worker_exception)
                else:
                    if not skip_raise_exception_arg:
                        raise thread_arg.worker_exception
            else:
                if on_thread_finish_arg:
                    on_thread_finish_arg()

        if threading.current_thread() != threading.main_thread():
            # starting thread from another thread causes an issue of not passing arguments'
            # values to on_thread_finished_int function, so on_thread_finish is not called
            st = traceback.format_stack()
            logging.error('Running thread from inside another thread. Stack: \n' + ''.join(st))

        thread = WorkerThread(parent=parent, worker_fun=worker_fun, worker_fun_args=worker_fun_args)

        # in Python 3.5 local variables sometimes are removed before calling on_thread_finished_int
        # so we have to bind that variables with the function ref
        bound_on_thread_finished = partial(on_thread_finished_int, thread, on_thread_finish, skip_raise_exception,
                                           on_thread_exception)

        thread.finished.connect(bound_on_thread_finished)
        thread.start()
        logging.debug('Started WorkerThread for: ' + str(worker_fun))
        return thread 
Example #20
Source File: test_signal.py    From oss-ftp with MIT License 5 votes vote down vote up
def format_frame(self, frame, limit=None):
        return ''.join(traceback.format_stack(frame, limit=limit)) 
Example #21
Source File: ioloop.py    From viewfinder with Apache License 2.0 5 votes vote down vote up
def log_stack(self, signal, frame):
        """Signal handler to log the stack trace of the current thread.

        For use with `set_blocking_signal_threshold`.
        """
        gen_log.warning('IOLoop blocked for %f seconds in\n%s',
                        self._blocking_signal_threshold,
                        ''.join(traceback.format_stack(frame))) 
Example #22
Source File: ioloop.py    From viewfinder with Apache License 2.0 5 votes vote down vote up
def log_stack(self, signal, frame):
        """Signal handler to log the stack trace of the current thread.

        For use with `set_blocking_signal_threshold`.
        """
        gen_log.warning('IOLoop blocked for %f seconds in\n%s',
                        self._blocking_signal_threshold,
                        ''.join(traceback.format_stack(frame))) 
Example #23
Source File: ioloop.py    From Computable with MIT License 5 votes vote down vote up
def log_stack(self, signal, frame):
        """Signal handler to log the stack trace of the current thread.

        For use with `set_blocking_signal_threshold`.
        """
        gen_log.warning('IOLoop blocked for %f seconds in\n%s',
                        self._blocking_signal_threshold,
                        ''.join(traceback.format_stack(frame))) 
Example #24
Source File: test_signal.py    From BinderFilter with MIT License 5 votes vote down vote up
def format_frame(self, frame, limit=None):
        return ''.join(traceback.format_stack(frame, limit=limit)) 
Example #25
Source File: Command.py    From PyEngine3D with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def getTraceCallStack():
    for line in traceback.format_stack()[::-1]:
        m = re.match(reTraceStack, line.strip())
        if m:
            filename = m.groups()[0]
            # ignore case
            if filename == __file__:
                continue
            filename = os.path.split(filename)[1]
            lineNumber = m.groups()[1]
            return "[%s:%s]" % (filename, lineNumber)
    return ""


# COMMANDS 
Example #26
Source File: util.py    From buttersink with GNU General Public License v3.0 5 votes vote down vote up
def displayTraceBack():
    """ Display traceback useful for debugging. """
    tb = traceback.format_stack()
    return "\n" + "".join(tb[:-1]) 
Example #27
Source File: api_test_base.py    From aliyun-tablestore-python-sdk with MIT License 5 votes vote down vote up
def assert_equal(self, res, expect_res):
        if isinstance(res, six.binary_type):
            res = res.decode('utf-8')
        if isinstance(expect_res, six.binary_type):
            expect_res = expect_res.decode('utf-8')

        if res != expect_res:
            #self.logger.warn("\nAssertion Failed\nactual: %s\nexpect: %s\n" % (res.decode('utf-8'), expect_res.decode('utf-8')) + "".join(traceback.format_stack()))
            self.assertEqual(res, expect_res) 
Example #28
Source File: api_test_base.py    From aliyun-tablestore-python-sdk with MIT License 5 votes vote down vote up
def assert_false(self):
        self.logger.warn("\nAssertion Failed\n" + "".join(traceback.format_stack()))
        raise AssertionError 
Example #29
Source File: debug.py    From miRge with GNU General Public License v3.0 5 votes vote down vote up
def bt():
    '''
    Print the calls stack.
    '''
    for line in traceback.format_stack()[:-1]:
        print line.strip() 
Example #30
Source File: helpers.py    From clusterfuzz with Apache License 2.0 5 votes vote down vote up
def __init__(self, message, status, trace_dump=None):
    super(EarlyExitException, self).__init__(message)
    self.status = status
    self.trace_dump = trace_dump
    if self.trace_dump is None:
      if sys.exc_info()[0] is not None:
        self.trace_dump = traceback.format_exc()
      else:
        self.trace_dump = ''.join(traceback.format_stack())