Python traceback.format_list() Examples

The following are code examples for showing how to use traceback.format_list(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: pyblish-win   Author: pyblish   File: code.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def showtraceback(self):
        """Display the exception that just occurred.

        We remove the first stack item because it is our own code.

        The output is written by self.write(), below.

        """
        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) 
Example 2
Project: PyPadPlusPlus   Author: bitagoras   File: pyPadRemoteClient.py    GNU General Public License v3.0 6 votes vote down vote up
def showtraceback(self):
        """Display the exception that just occurred.
        The first two stack items are removed because it is
        not the user code."""
        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[:2]
            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(sys.stderr, list) 
Example 3
Project: PyPadPlusPlus   Author: bitagoras   File: pyPadClient.py    GNU General Public License v3.0 6 votes vote down vote up
def showtraceback(self):
        """Display the exception that just occurred."""
        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[:2]
            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(sys.stderr, list) 
Example 4
Project: vscode-mayapy   Author: FXTD-ODYSSEY   File: futures.py    MIT License 6 votes vote down vote up
def __del__(self):
        # Do not run any checks if Python is shutting down.
        if not sys or not self._lock:
            return

        with self._lock:
            assert self._done or self._done is None
            exc_info = self._exc_info
            if exc_info and not self._observed:
                msg = 'Unobserved failed future'
                origin = self._origin
                if origin:
                    origin = '\n'.join(traceback.format_list(origin))
                    msg += ' originating from:\n\n{origin}\n\n'
                ptvsd.log.exception(msg, origin=origin, exc_info=exc_info)
                traceback.print_exception(*exc_info, file=sys.__stderr__) 
Example 5
Project: vscode-mayapy   Author: FXTD-ODYSSEY   File: pydevconsole_code_for_ironpython.py    MIT License 6 votes vote down vote up
def showtraceback(self, *args, **kwargs):
        """Display the exception that just occurred.

        We remove the first stack item because it is our own code.

        The output is written by self.write(), below.

        """
        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) 
Example 6
Project: vscode-mayapy   Author: FXTD-ODYSSEY   File: pydevconsole.py    MIT License 6 votes vote down vote up
def showtraceback(self, *args, **kwargs):
        """Display the exception that just occurred."""
        # 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)) 
Example 7
Project: datasette   Author: simonw   File: tracer.py    Apache License 2.0 6 votes vote down vote up
def trace(type, **kwargs):
    assert not TRACE_RESERVED_KEYS.intersection(
        kwargs.keys()
    ), ".trace() keyword parameters cannot include {}".format(TRACE_RESERVED_KEYS)
    task_id = get_task_id()
    if task_id is None:
        yield
        return
    tracer = tracers.get(task_id)
    if tracer is None:
        yield
        return
    start = time.time()
    yield
    end = time.time()
    trace_info = {
        "type": type,
        "start": start,
        "end": end,
        "duration_ms": (end - start) * 1000,
        "traceback": traceback.format_list(traceback.extract_stack(limit=6)[:-3]),
    }
    trace_info.update(kwargs)
    tracer.append(trace_info) 
Example 8
Project: ironpython2   Author: IronLanguages   File: code.py    Apache License 2.0 6 votes vote down vote up
def showtraceback(self):
        """Display the exception that just occurred.

        We remove the first stack item because it is our own code.

        The output is written by self.write(), below.

        """
        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) 
Example 9
Project: IronHydra   Author: microdee   File: code.py    MIT License 6 votes vote down vote up
def showtraceback(self):
        """Display the exception that just occurred.

        We remove the first stack item because it is our own code.

        The output is written by self.write(), below.

        """
        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) 
Example 10
Project: Computable   Author: ktraunmueller   File: code.py    MIT License 6 votes vote down vote up
def showtraceback(self):
        """Display the exception that just occurred.

        We remove the first stack item because it is our own code.

        The output is written by self.write(), below.

        """
        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) 
Example 11
Project: ableton-live-webapi   Author: valsteen   File: code.py    The Unlicense 6 votes vote down vote up
def showtraceback(self):
        """Display the exception that just occurred.

        We remove the first stack item because it is our own code.

        The output is written by self.write(), below.

        """
        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) 
Example 12
Project: oss-ftp   Author: aliyun   File: code.py    MIT License 6 votes vote down vote up
def showtraceback(self):
        """Display the exception that just occurred.

        We remove the first stack item because it is our own code.

        The output is written by self.write(), below.

        """
        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) 
Example 13
Project: streamlink   Author: streamlink   File: session.py    BSD 2-Clause "Simplified" License 6 votes vote down vote up
def print_small_exception(start_after):
    type, value, traceback_ = sys.exc_info()

    tb = traceback.extract_tb(traceback_)
    index = 0

    for i, trace in enumerate(tb):
        if trace[2] == start_after:
            index = i + 1
            break

    lines = traceback.format_list(tb[index:])
    lines += traceback.format_exception_only(type, value)

    for line in lines:
        sys.stderr.write(line)

    sys.stderr.write("\n") 
Example 14
Project: profitpy   Author: hpsilva   File: shell.py    GNU General Public License v2.0 6 votes vote down vote up
def showtraceback(self):
        """ Display the exception that just occurred.

        We remove the first stack item because it is our own code.

        The output is written by self.write(), below.
        """
        try:
            type, value, tb = sys.exc_info()
            sys.last_type = type
            sys.last_value = value
            sys.last_traceback = tb
            tblist = extract_tb(tb)
            del tblist[:1]
            seq = format_list(tblist)
            if seq:
                seq.insert(0, 'Traceback (most recent call last):\n')
            seq[len(seq):] = format_exception_only(type, value)
        finally:
            tblist = tb = None
        parent = self.parent
        for line, color in zip(seq, cycle(('#0000cc', '#0000cc', '#cc0000'))):
            self.write(line) 
Example 15
Project: clikit   Author: sdispater   File: exception_trace.py    MIT License 5 votes vote down vote up
def _render_traceback(self, io, tb):  # type: (IO, ...) -> None
        frames = []
        while tb:
            frames.append(self._format_traceback_frame(io, tb))

            tb = tb.tb_next

        io.write_line("<b>Traceback (most recent call last):</b>")
        io.write_line("".join(traceback.format_list(frames))) 
Example 16
Project: hive-presto-docker   Author: dinhnhatbang   File: util.py    GNU General Public License v3.0 5 votes vote down vote up
def full_stack():
    exc = sys.exc_info()[0]
    stack = traceback.extract_stack()[:-1]  # last one would be full_stack()
    if not exc is None:  # i.e. if an exception is present
        del stack[-1]       # remove call of full_stack, the printed exception
                            # will contain the caught exception caller instead
    trc = 'Traceback (most recent call last):\n'
    stackstr = trc + ''.join(traceback.format_list(stack))
    if not exc is None:
         stackstr += '  ' + traceback.format_exc().lstrip(trc)
    return stackstr 
Example 17
Project: Repobot   Author: Desgard   File: exceptions.py    MIT License 5 votes vote down vote up
def get_trace(self):
        '''This returns an abbreviated stack trace with lines that only concern
        the caller. In other words, the stack trace inside the Pexpect module
        is not included. '''

        tblist = traceback.extract_tb(sys.exc_info()[2])
        tblist = [item for item in tblist if ('pexpect/__init__' not in item[0])
                                           and ('pexpect/expect' not in item[0])]
        tblist = traceback.format_list(tblist)
        return ''.join(tblist) 
Example 18
Project: threat_intel   Author: Yelp   File: error_messages.py    MIT License 5 votes vote down vote up
def write_exception(e):
    exc_type, __, exc_traceback = sys.exc_info()
    sys.stderr.write('[ERROR] {0} {1}\n'.format(exc_type.__name__, str(e)))
    for line in format_list(extract_tb(exc_traceback)):
        sys.stderr.write(line) 
Example 19
Project: chattR   Author: patrickstocklin   File: debug.py    GNU General Public License v2.0 5 votes vote down vote up
def format_exception(self):
        """
        Return the same data as from traceback.format_exception.
        """
        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 
Example 20
Project: NiujiaoDebugger   Author: MrSrc   File: coroutines.py    GNU General Public License v3.0 5 votes vote down vote up
def __del__(self):
        # Be careful accessing self.gen.frame -- self.gen might not exist.
        gen = getattr(self, 'gen', None)
        frame = getattr(gen, 'gi_frame', None)
        if frame is not None and frame.f_lasti == -1:
            msg = f'{self!r} was never yielded from'
            tb = getattr(self, '_source_traceback', ())
            if tb:
                tb = ''.join(traceback.format_list(tb))
                msg += (f'\nCoroutine object created at '
                        f'(most recent call last, truncated to '
                        f'{constants.DEBUG_STACK_DEPTH} last lines):\n')
                msg += tb.rstrip()
            logger.error(msg) 
Example 21
Project: NiujiaoDebugger   Author: MrSrc   File: warnings.py    GNU General Public License v3.0 5 votes vote down vote up
def _warn_unawaited_coroutine(coro):
    msg_lines = [
        f"coroutine '{coro.__qualname__}' was never awaited\n"
    ]
    if coro.cr_origin is not None:
        import linecache, traceback
        def extract():
            for filename, lineno, funcname in reversed(coro.cr_origin):
                line = linecache.getline(filename, lineno)
                yield (filename, lineno, funcname, line)
        msg_lines.append("Coroutine created at (most recent call last)\n")
        msg_lines += traceback.format_list(list(extract()))
    msg = "".join(msg_lines).rstrip("\n")
    # Passing source= here means that if the user happens to have tracemalloc
    # enabled and tracking where the coroutine was created, the warning will
    # contain that traceback. This does mean that if they have *both*
    # coroutine origin tracking *and* tracemalloc enabled, they'll get two
    # partially-redundant tracebacks. If we wanted to be clever we could
    # probably detect this case and avoid it, but for now we don't bother.
    warn(msg, category=RuntimeWarning, stacklevel=2, source=coro)


# filters contains a sequence of filter 5-tuples
# The components of the 5-tuple are:
# - an action: error, ignore, always, default, module, or once
# - a compiled regex that must match the warning message
# - a class representing the warning category
# - a compiled regex that must match the module that is being warned
# - a line number for the line being warning, or 0 to mean any line
# If either if the compiled regexs are None, match anything. 
Example 22
Project: crosswalk-odroid-ucc   Author: UCC-Organism   File: build_utils.py    MIT License 5 votes vote down vote up
def CheckCallDie(args, suppress_output=False, cwd=None):
  if not cwd:
    cwd = os.getcwd()

  if os.name == 'posix':
    child = subprocess.Popen(args,
        stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=cwd)
  else:
    child = subprocess.Popen(args,
        stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=cwd, shell=True)

  stdout, _ = child.communicate()

  if child.returncode:
    stacktrace = traceback.extract_stack()
    print >> sys.stderr, ''.join(traceback.format_list(stacktrace))
    # A user should be able to simply copy and paste the command that failed
    # into their shell.
    copyable_command = ' '.join(map(pipes.quote, args))
    copyable_command = ('( cd ' + os.path.abspath(cwd) + '; '
        + copyable_command + ' )')
    print >> sys.stderr, 'Command failed:', copyable_command, '\n'

    if stdout:
      print stdout

    # Directly exit to avoid printing stacktrace.
    sys.exit(child.returncode)

  else:
    if stdout and not suppress_output:
      print stdout
    return stdout 
Example 23
Project: chainer-deconv   Author: germanRos   File: variable.py    MIT License 5 votes vote down vote up
def _check_grad_type(func, x, gx):
    def make_message(message):
        if func:
            detail = 'Function `{0}` ({1}) has a bug.\n'.format(
                type(func).__name__, func.label)

            stack = func.stack
            if stack:
                detail += 'Stacktrace of the function is below:\n'
                for line in traceback.format_list(func._stack):
                    detail += line

            detail += '''
Please report this error to the issue tracker with the stack trace,
the information of your environment, and your script:
https://github.com/pfnet/chainer/issues/new.
'''.format(type(func).__name__, func.label)

        else:
            detail = ''

        detail += message
        return detail

    if not isinstance(gx, type(x.data)):
        msg = ('Type of data and grad mismatch\n%s != %s' %
               (type(x.data), type(gx)))
        raise TypeError(make_message(msg))
    if gx.dtype != x.data.dtype:
        msg = ('Dtype of data and grad mismatch\n%s != %s' %
               (x.data.dtype, gx.dtype))
        raise TypeError(make_message(msg))
    if gx.shape != x.data.shape:
        msg = ('Shape of data and grad mismatch\n%s != %s' %
               (x.data.shape, gx.shape))
        raise ValueError(make_message(msg)) 
Example 24
Project: valinor   Author: ARMmbed   File: gdb.py    Apache License 2.0 5 votes vote down vote up
def _ignoreSignal(signum, frame):
    logging.debug('ignoring signal %s, traceback:\n%s' % (
        signum, ''.join(traceback.format_list(traceback.extract_stack(frame)))
    )) 
Example 25
Project: TESTGIT   Author: B-ROY   File: debug.py    Apache License 2.0 5 votes vote down vote up
def format_exception(self):
        """
        Return the same data as from traceback.format_exception.
        """
        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 
Example 26
Project: AneMo   Author: jspargo   File: debug.py    GNU General Public License v2.0 5 votes vote down vote up
def format_exception(self):
        """
        Return the same data as from traceback.format_exception.
        """
        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 
Example 27
Project: asynq   Author: quora   File: debug.py    Apache License 2.0 5 votes vote down vote up
def format_tb(tb):
    """Formats a traceback into a list of lines."""
    return traceback.format_list(extract_tb(tb)) 
Example 28
Project: asynq   Author: quora   File: debug.py    Apache License 2.0 5 votes vote down vote up
def dump_stack(skip=0, limit=None):
    """Dumps current stack trace."""
    skip += 2  # To skip dump_stack and traceback.extract_stack
    if limit is None:
        limit = options.STACK_DUMP_LIMIT
    print('--- Stack trace: -----------------------------------------------------')
    try:
        stack = traceback.extract_stack(limit=None if limit is None else limit + skip)
        print(''.join(traceback.format_list(stack[:-skip])), end='')
    finally:
        print('----------------------------------------------------------------------')
        stdout.flush() 
Example 29
Project: asynq   Author: quora   File: debug.py    Apache License 2.0 5 votes vote down vote up
def dump_asynq_stack():
    """Dumps the current asynq stack to stdout."""
    format_list = format_asynq_stack()
    if format_list is None:
        print('dump_asynq_stack: no asynq task currently active')
    else:
        print('\n'.join(format_list)) 
Example 30
Project: dockerizeme   Author: dockerizeme   File: snippet.py    Apache License 2.0 5 votes vote down vote up
def load_handler_failed_handler(e, modname):
    if isinstance(e, ImportError):
        return make_fault_handler(wsgi.FaultException("Unable to import module '{}'".format(modname), str(e), None))
    elif isinstance(e, SyntaxError):
        trace = "File \"%s\" Line %s\n\t%s" % (e.filename, e.lineno, e.text)
        fault = wsgi.FaultException("Syntax error in module '{}'".format(modname), str(e), trace)
    else:
        exc_info = sys.exc_info()
        trace = traceback.format_list(traceback.extract_tb(exc_info[2]))
        fault = wsgi.FaultException("module initialization error", str(e), trace[1:])
    return make_fault_handler(fault) 
Example 31
Project: dockerizeme   Author: dockerizeme   File: snippet.py    Apache License 2.0 5 votes vote down vote up
def report_fault_helper(invokeid, exc_info, msg):
    etype, value, tb = exc_info
    if msg:
        msgs = [msg, str(value)]
    else:
        msgs = [str(value), etype.__name__]

    tb_tuples = extract_traceback(tb)

    if sys.version_info[0] >= 3:
        awesome_range = range
    else:
        awesome_range = xrange

    for i in awesome_range(len(tb_tuples)):
        if "/bootstrap.py" not in tb_tuples[i][0]:  # filename of the tb tuple
            tb_tuples = tb_tuples[i:]
            break

    lambda_runtime.report_fault(
        invokeid,
        msgs[0],
        msgs[1],
        (
            "Traceback (most recent call last):\n"
            + ''.join(traceback.format_list(tb_tuples))
            + ''.join(traceback.format_exception_only(etype, value))
        )
    )
    report_xray_fault_helper(etype.__name__, msgs[0], tb_tuples)

    return make_error(str(value), etype.__name__, tb_tuples) 
Example 32
Project: dockerizeme   Author: dockerizeme   File: snippet.py    Apache License 2.0 5 votes vote down vote up
def _display_intercepted_call(annotated_tb):
    msg = 'DB write to {obj} ({oid}) from "{filename}", line {line_no}'
    msg = msg.format(**annotated_tb._asdict())
    print "=" * len(msg)
    print msg
    print "=" * len(msg)
    print ''.join(traceback.format_list(annotated_tb.extracted_tb)) 
Example 33
Project: GTDWeb   Author: lanbing510   File: debug.py    GNU General Public License v2.0 5 votes vote down vote up
def format_exception(self):
        """
        Return the same data as from traceback.format_exception.
        """
        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 
Example 34
Project: liberator   Author: libscie   File: debug.py    Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def format_exception(self):
        """
        Return the same data as from traceback.format_exception.
        """
        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 
Example 35
Project: D-VAE   Author: muhanzhang   File: link.py    MIT License 5 votes vote down vote up
def log_thunk_trace(value, f=sys.stderr):
    """
    Log Theano's diagnostic stack trace for an exception
    raised by raise_with_op.

    """
    # in future, consider accepting `write` as arg rather than file
    # to support writing to a logger
    def write(msg):
        print("log_thunk_trace: %s" % msg.strip(), file=f)

    if hasattr(value, '__thunk_trace__'):
        trace2 = value.__thunk_trace__
        write("There was a problem executing an Op.")
        if trace2 is None:
            write("Could not find where this Op was defined.")
            write(" * You might have instantiated this Op "
                  "directly instead of using a constructor.")
            write(" * The Op you constructed might have been"
                  " optimized. Try turning off optimizations.")
        elif trace2:
            write("Definition in: ")
            for line in traceback.format_list(trace2):
                write(line)
            write("For the full definition stack trace set"
                  " the Theano flags traceback.limit to -1") 
Example 36
Project: code-inspector   Author: maxim5   File: 99dd30daa3dfa0e0f34418b6ca363dae_futures.py    Apache License 2.0 5 votes vote down vote up
def __del__(self):
        if self.tb:
            msg = 'Future/Task exception was never retrieved\n'
            if self.source_traceback:
                src = ''.join(traceback.format_list(self.source_traceback))
                msg += 'Future/Task created at (most recent call last):\n'
                msg += '%s\n' % src.rstrip()
            msg += ''.join(self.tb).rstrip()
            self.loop.call_exception_handler({'message': msg}) 
Example 37
Project: open-recipe   Author: dspray95   File: error.py    The Unlicense 5 votes vote down vote up
def __repr__(self):
        """
        Present a string representation which includes a template traceback, so
        we can tell where this error occurred in the template, as well as in
        Python.
        """
        # Avoid importing things unnecessarily until we actually need them;
        # since this is an 'error' module we should be extra paranoid about
        # that.
        from traceback import format_list
        if self._roots:
            roots = '  ' + '\n  '.join([
                    self._formatRoot(r) for r in self._roots]) + '\n'
        else:
            roots = ''
        if self._traceback:
            traceback = '\n'.join([
                    line
                    for entry in format_list(self._traceback)
                    for line in entry.splitlines()]) + '\n'
        else:
            traceback = ''
        return (
            'Exception while flattening:\n' +
            roots + traceback +
            self._exception.__class__.__name__ + ': ' +
            str(self._exception) + '\n') 
Example 38
Project: Blockly-rduino-communication   Author: technologiescollege   File: futures.py    GNU General Public License v3.0 5 votes vote down vote up
def __del__(self):
        if self.tb:
            msg = 'Future/Task exception was never retrieved\n'
            if self.source_traceback:
                src = ''.join(traceback.format_list(self.source_traceback))
                msg += 'Future/Task created at (most recent call last):\n'
                msg += '%s\n' % src.rstrip()
            msg += ''.join(self.tb).rstrip()
            self.loop.call_exception_handler({'message': msg}) 
Example 39
Project: Blockly-rduino-communication   Author: technologiescollege   File: coroutines.py    GNU General Public License v3.0 5 votes vote down vote up
def __del__(self):
        # Be careful accessing self.gen.frame -- self.gen might not exist.
        gen = getattr(self, 'gen', None)
        frame = getattr(gen, 'gi_frame', None)
        if frame is None:
            frame = getattr(gen, 'cr_frame', None)
        if frame is not None and frame.f_lasti == -1:
            msg = '%r was never yielded from' % self
            tb = getattr(self, '_source_traceback', ())
            if tb:
                tb = ''.join(traceback.format_list(tb))
                msg += ('\nCoroutine object created at '
                        '(most recent call last):\n')
                msg += tb.rstrip()
            logger.error(msg) 
Example 40
Project: Blockly-rduino-communication   Author: technologiescollege   File: code.py    GNU General Public License v3.0 5 votes vote down vote up
def showtraceback(self):
        """Display the exception that just occurred.

        We remove the first stack item because it is our own code.

        The output is written by self.write(), below.

        """
        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
        if sys.excepthook is sys.__excepthook__:
            self.write(''.join(lines))
        else:
            # If someone has set sys.excepthook, we let that take precedence
            # over self.write
            sys.excepthook(type, value, tb) 
Example 41
Project: Blockly-rduino-communication   Author: technologiescollege   File: repl.py    GNU General Public License v3.0 5 votes vote down vote up
def _handle_exception(cls, cli, e):
        output = cli.output

        # Instead of just calling ``traceback.format_exc``, we take the
        # traceback and skip the bottom calls of this framework.
        t, v, tb = sys.exc_info()
        tblist = traceback.extract_tb(tb)

        for line_nr, tb_tuple in enumerate(tblist):
            if tb_tuple[0] == '<stdin>':
                tblist = tblist[line_nr:]
                break

        l = traceback.format_list(tblist)
        if l:
            l.insert(0, "Traceback (most recent call last):\n")
        l.extend(traceback.format_exception_only(t, v))

        # For Python2: `format_list` and `format_exception_only` return
        # non-unicode strings. Ensure that everything is unicode.
        if six.PY2:
            l = [i.decode('utf-8') if isinstance(i, six.binary_type) else i for i in l]

        tb = ''.join(l)

        # Format exception and write to output.
        # (We use the default style. Most other styles result
        # in unreadable colors for the traceback.)
        tokens = _lex_python_traceback(tb)
        cli.print_tokens(tokens, style=style_from_pygments(DefaultStyle))

        output.write('%s\n' % e)
        output.flush() 
Example 42
Project: pyreload   Author: pyreload   File: misc.py    GNU General Public License v3.0 5 votes vote down vote up
def format_exc(frame=None):
    """
    Format call-stack and display exception information (if availible)
    """
    exc_info = sys.exc_info()
    exc_desc = ""

    callstack = traceback.extract_stack(frame)
    callstack = callstack[:-1]

    if exc_info[0] is not None:
        exception_callstack = traceback.extract_tb(exc_info[2])

        # @NOTE: Does this exception belongs to us?
        if callstack[-1][0] == exception_callstack[0][0]:
            callstack = callstack[:-1]
            callstack.extend(exception_callstack)
            exc_desc = decode(
                "".join(
                    traceback.format_exception_only(
                        exc_info[0],
                        exc_info[1])))

    msg = "Traceback (most recent call last):\n"
    msg += decode("".join(traceback.format_list(callstack)))
    msg += exc_desc

    return msg 
Example 43
Project: Fun5G   Author: OpenWinCon   File: debug.py    Apache License 2.0 5 votes vote down vote up
def format_exception(self):
        """
        Return the same data as from traceback.format_exception.
        """
        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 
Example 44
Project: Comparative-Annotation-Toolkit   Author: ComparativeGenomicsToolkit   File: __init__.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, msg, cause=None):
        """Constructor."""
        if (cause is not None) and (not isinstance(cause, PycbioException)):
            # store stack trace in other Exception types
            exi = sys.exc_info()
            if exi is not None:
                setattr(cause, "stackTrace", traceback.format_list(traceback.extract_tb(exi[2])))
        Exception.__init__(self, msg)
        self.msg = msg
        self.cause = cause
        self.stackTrace = traceback.format_list(traceback.extract_stack())[0:-1] 
Example 45
Project: Comparative-Annotation-Toolkit   Author: ComparativeGenomicsToolkit   File: pipeline.py    Apache License 2.0 5 votes vote down vote up
def __cleanupDev(self, dev):
        try:
            dev.finish()
        except Exception as ex:
            # FIXME: make optional, or record, or something
            exi = sys.exc_info()
            stack = "" if exi is None else "".join(traceback.format_list(traceback.extract_tb(exi[2])))+"\n"
            sys.stderr.write("ProcDag dev cleanup exception: " +str(ex)+"\n"+stack) 
Example 46
Project: youtube-dl   Author: marado   File: YoutubeDL.py    The Unlicense 5 votes vote down vote up
def trouble(self, message=None, tb=None):
        """Determine action to take when a download problem appears.

        Depending on if the downloader has been configured to ignore
        download errors or not, this method may throw an exception or
        not when errors are found, after printing the message.

        tb, if given, is additional traceback information.
        """
        if message is not None:
            self.to_stderr(message)
        if self.params.get('verbose'):
            if tb is None:
                if sys.exc_info()[0]:  # if .trouble has been called from an except block
                    tb = ''
                    if hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
                        tb += ''.join(traceback.format_exception(*sys.exc_info()[1].exc_info))
                    tb += compat_str(traceback.format_exc())
                else:
                    tb_data = traceback.format_list(traceback.extract_stack())
                    tb = ''.join(tb_data)
            self.to_stderr(tb)
        if not self.params.get('ignoreerrors', False):
            if sys.exc_info()[0] and hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
                exc_info = sys.exc_info()[1].exc_info
            else:
                exc_info = sys.exc_info()
            raise DownloadError(message, exc_info)
        self._download_retcode = 1 
Example 47
Project: Vigtech-Services   Author: VigTech   File: debug.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def format_exception(self):
        """
        Return the same data as from traceback.format_exception.
        """
        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 
Example 48
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: coroutines.py    GNU General Public License v2.0 5 votes vote down vote up
def __del__(self):
        # Be careful accessing self.gen.frame -- self.gen might not exist.
        gen = getattr(self, 'gen', None)
        frame = getattr(gen, 'gi_frame', None)
        if frame is not None and frame.f_lasti == -1:
            msg = f'{self!r} was never yielded from'
            tb = getattr(self, '_source_traceback', ())
            if tb:
                tb = ''.join(traceback.format_list(tb))
                msg += (f'\nCoroutine object created at '
                        f'(most recent call last, truncated to '
                        f'{constants.DEBUG_STACK_DEPTH} last lines):\n')
                msg += tb.rstrip()
            logger.error(msg) 
Example 49
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: warnings.py    GNU General Public License v2.0 5 votes vote down vote up
def _warn_unawaited_coroutine(coro):
    msg_lines = [
        f"coroutine '{coro.__qualname__}' was never awaited\n"
    ]
    if coro.cr_origin is not None:
        import linecache, traceback
        def extract():
            for filename, lineno, funcname in reversed(coro.cr_origin):
                line = linecache.getline(filename, lineno)
                yield (filename, lineno, funcname, line)
        msg_lines.append("Coroutine created at (most recent call last)\n")
        msg_lines += traceback.format_list(list(extract()))
    msg = "".join(msg_lines).rstrip("\n")
    # Passing source= here means that if the user happens to have tracemalloc
    # enabled and tracking where the coroutine was created, the warning will
    # contain that traceback. This does mean that if they have *both*
    # coroutine origin tracking *and* tracemalloc enabled, they'll get two
    # partially-redundant tracebacks. If we wanted to be clever we could
    # probably detect this case and avoid it, but for now we don't bother.
    warn(msg, category=RuntimeWarning, stacklevel=2, source=coro)


# filters contains a sequence of filter 5-tuples
# The components of the 5-tuple are:
# - an action: error, ignore, always, default, module, or once
# - a compiled regex that must match the warning message
# - a class representing the warning category
# - a compiled regex that must match the module that is being warned
# - a line number for the line being warning, or 0 to mean any line
# If either if the compiled regexs are None, match anything. 
Example 50
Project: DroidPot   Author: WhySoGeeky   File: debug.py    MIT License 5 votes vote down vote up
def format_exception(self):
        """
        Return the same data as from traceback.format_exception.
        """
        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