Python traceback.format_list() Examples

The following are 30 code examples of traceback.format_list(). 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: utils.py    From janus-cloud with GNU Affero General Public License v3.0 6 votes vote down vote up
def error_to_janus_msg(session_id=0, transaction=None, exception=None):
    """ convert a Error exception to a message in dict form """
    error = {}
    if isinstance(exception, JanusCloudError):
        error["code"] = exception.code
        error["reason"] = str(exception)
    elif isinstance(exception, SchemaError):
        error["code"] = JANUS_ERROR_INVALID_ELEMENT_TYPE
        error["reason"] = str(exception)
    else:
        error["code"] = 500
        error["reason"] = str(exception)

    type, dummy, tb = sys.exc_info()
    tb_list = traceback.format_list(traceback.extract_tb(tb)[-10:])
    error["traceback"] = tb_list
    return create_janus_msg("error", session_id, transaction, error=error) 
Example #2
Source File: exceptions.py    From botoflow with Apache License 2.0 6 votes vote down vote up
def format_exc(self, limit=None):
        """
        This is like exception.print_exc(limit) but returns a string instead
        of printing to a file.
        """
        result = ["Traceback (most recent call last):\n"]

        tb_list = self._traceback

        if limit is not None:
            tb_list = tb_list[-limit:]

        result.extend(traceback.format_list(tb_list))

        if self.cause is not None:
            result.extend(traceback.format_exception_only(self.cause.__class__,
                                                          self.cause))
            return result
        else:
            return result 
Example #3
Source File: code.py    From meddle with 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 #4
Source File: asyncio_tools.py    From rssant with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _format_stack(task, coro, complete=False):
    '''
    Formats a traceback from a stack of coroutines/generators
    '''
    dirname = os.path.dirname(__file__)
    extracted_list = []
    checked = set()
    for f in _get_stack(coro):
        lineno = f.f_lineno
        co = f.f_code
        filename = co.co_filename
        name = co.co_name
        if not complete and os.path.dirname(filename) == dirname:
            continue
        if filename not in checked:
            checked.add(filename)
            linecache.checkcache(filename)
        line = linecache.getline(filename, lineno, f.f_globals)
        extracted_list.append((filename, lineno, name, line))
    if not extracted_list:
        resp = 'No stack for %r' % task
    else:
        resp = 'Stack for %r (most recent call last):\n' % task
        resp += ''.join(traceback.format_list(extracted_list))
    return resp 
Example #5
Source File: GameModel.py    From pychess with GNU General Public License v3.0 6 votes vote down vote up
def kill(self, reason):
        log.debug("GameModel.kill: players=%s, self.ply=%s: Killing a game for reason %d\n%s" % (
                  repr(self.players), str(self.ply), reason, "".join(
                      traceback.format_list(traceback.extract_stack())).strip()))

        self.status = KILLED
        self.reason = reason

        for player in self.players:
            player.end(self.status, reason)

        for spectator in self.spectators.values():
            spectator.end(self.status, reason)

        if self.timed:
            self.timemodel.end()

        self.emit("game_ended", reason) 
Example #6
Source File: serialization.py    From Penny-Dreadful-Tools with GNU General Public License v3.0 6 votes vote down vote up
def extra_serializer(obj: Any) -> Union[int, str, List[Any], Dict[str, Any]]:
    """JSON serializer for objects not serializable by default json code"""

    if isinstance(obj, datetime.datetime):
        return dtutil.dt2ts(obj)
    if isinstance(obj, bytes):
        return obj.decode('utf-8')
    if isinstance(obj, decimal.Decimal):
        return obj.to_eng_string()
    if isinstance(obj, (set, KeysView)):
        return list(obj)
    if isinstance(obj, Exception):
        stack = traceback.extract_tb(obj.__traceback__)
        return traceback.format_list(stack)
    if hasattr(obj, 'to_dict'):
        return obj.to_dict()
    if hasattr(obj, '__attrs_attrs__'):
        val: Dict[str, Any] = {}
        for a in obj.__attrs_attrs__:
            val[a.name] = getattr(obj, a.name)
        return val
    raise TypeError('Type {t} not serializable - {obj}'.format(t=type(obj), obj=obj)) 
Example #7
Source File: tracer.py    From datasette with 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
Source File: code.py    From ironpython2 with 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
Source File: async_traceback.py    From botoflow with Apache License 2.0 6 votes vote down vote up
def format_exc(limit=None, exception=None, tb_list=None):
    """
    This is like print_exc(limit) but returns a string instead of printing to a
    file.
    """
    result = ["Traceback (most recent call last):\n"]
    if exception is None:
        exception = get_context_with_traceback(get_async_context()).exception

    if tb_list is None:
        tb_list = extract_tb(limit)

    if tb_list:
        result.extend(traceback.format_list(tb_list))
        result.extend(traceback.format_exception_only(exception.__class__,
                                                      exception))
        return result
    else:
        return None 
Example #10
Source File: visualstudio_py_debugger.py    From iot-utilities with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def print_exception(exc_type, exc_value, exc_tb):
    # remove debugger frames from the top and bottom of the traceback
    tb = traceback.extract_tb(exc_tb)
    for i in [0, -1]:
        while tb:
            frame_file = path.normcase(tb[i][0])
            if not any(is_same_py_file(frame_file, f) for f in DONT_DEBUG):
                break
            del tb[i]

    # print the traceback
    if tb:
        print('Traceback (most recent call last):')
        for out in traceback.format_list(tb):
            sys.stderr.write(out)
    
    # print the exception
    for out in traceback.format_exception_only(exc_type, exc_value):
        sys.stdout.write(out) 
Example #11
Source File: visualstudio_py_debugger.py    From iot-utilities with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def print_exception(exc_type, exc_value, exc_tb):
    # remove debugger frames from the top and bottom of the traceback
    tb = traceback.extract_tb(exc_tb)
    for i in [0, -1]:
        while tb:
            frame_file = path.normcase(tb[i][0])
            if not any(is_same_py_file(frame_file, f) for f in DONT_DEBUG):
                break
            del tb[i]

    # print the traceback
    if tb:
        print('Traceback (most recent call last):')
        for out in traceback.format_list(tb):
            sys.stderr.write(out)
    
    # print the exception
    for out in traceback.format_exception_only(exc_type, exc_value):
        sys.stdout.write(out) 
Example #12
Source File: visualstudio_py_debugger.py    From iot-utilities with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def print_exception(exc_type, exc_value, exc_tb):
    # remove debugger frames from the top and bottom of the traceback
    tb = traceback.extract_tb(exc_tb)
    for i in [0, -1]:
        while tb:
            frame_file = path.normcase(tb[i][0])
            if not any(is_same_py_file(frame_file, f) for f in DONT_DEBUG):
                break
            del tb[i]

    # print the traceback
    if tb:
        print('Traceback (most recent call last):')
        for out in traceback.format_list(tb):
            sys.stderr.write(out)
    
    # print the exception
    for out in traceback.format_exception_only(exc_type, exc_value):
        sys.stdout.write(out) 
Example #13
Source File: code.py    From Computable with 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 #14
Source File: variable.py    From chainer with MIT License 6 votes vote down vote up
def _raise_grad_error(exc_type, func, msg):
    detail = ''
    if func:
        detail = 'Function `{0}` ({1}) has a bug.\n'.format(
            type(func)._impl_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/chainer/chainer/issues/new.
'''

    raise exc_type(detail + msg) 
Example #15
Source File: _backprop_utils.py    From chainer with MIT License 6 votes vote down vote up
def _reraise_with_stack(func, e):
    if func.stack is not None:
        # Reraise any type of exceptions including the following:
        # - Chainer raises RuntimeError for NaN values; and
        # - NumPy raises FloatingPointError for invalid values.

        # TODO(kataoka): unify variable._check_grad_type and below
        additional_message = \
            '\n{}\nStacktrace of the function is below:\n{}'.format(
                '-' * _get_columns(),
                ''.join(traceback.format_list(func.stack[:-1])))
        if e.args:
            e.args = (e.args[0] + additional_message,) + e.args[1:]
        else:
            e.args = (additional_message,)
    raise 
Example #16
Source File: session.py    From streamlink with 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 #17
Source File: pydevconsole.py    From PyDev.Debugger with Eclipse Public License 1.0 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 #18
Source File: pydevconsole_code_for_ironpython.py    From PyDev.Debugger with Eclipse Public License 1.0 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 #19
Source File: code.py    From oss-ftp with 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 #20
Source File: code.py    From BinderFilter with 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 #21
Source File: visualstudio_py_debugger.py    From iot-utilities with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def print_exception(exc_type, exc_value, exc_tb):
    # remove debugger frames from the top and bottom of the traceback
    tb = traceback.extract_tb(exc_tb)
    for i in [0, -1]:
        while tb:
            frame_file = path.normcase(tb[i][0])
            if not any(is_same_py_file(frame_file, f) for f in DONT_DEBUG):
                break
            del tb[i]

    # print the traceback
    if tb:
        print('Traceback (most recent call last):')
        for out in traceback.format_list(tb):
            sys.stderr.write(out)
    
    # print the exception
    for out in traceback.format_exception_only(exc_type, exc_value):
        sys.stdout.write(out) 
Example #22
Source File: __init__.py    From flappy-bird-py with GNU General Public License v2.0 5 votes vote down vote up
def __getattr__(self, name):
            fn = getattr(self.lib, name)
            def f(*args):
                _SetLastError(0)
                result = fn(*args)
                err = _GetLastError()
                if err != 0:
                    map(_log_win32.write,
                        traceback.format_list(traceback.extract_stack()[:-1]))
                    print >> _log_win32, format_error(err)
                return result
            return f 
Example #23
Source File: exceptions.py    From neuralmonkey with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __str__(self) -> str:
        """Convert this exception to string."""

        trc = "".join(traceback.format_list(traceback.extract_tb(
            self.original_exception.__traceback__)))
        return "Error while loading '{}': {}\nTraceback: {}".format(
            self.object_name, self.original_exception, trc) 
Example #24
Source File: testcase.py    From script-languages with MIT License 5 votes vote down vote up
def __getattr__(self, name):
        if name.startswith('expect'):
            # replace expectFoo with assertFoo
            newname = name.replace('expect', 'assert', 1)
            try:
                newattr = getattr(self, newname)
                def wrapper(*args, **kwargs):
                    self._needs_assertExpectations = True
                    try:
                        newattr(*args, **kwargs)
                    except self.failureException as e:
                        stack = traceback.extract_stack()
                        stack = reversed(stack)
                        stack = itertools.takewhile(lambda x: "testMethod()" not in x, stack)
                        stack = itertools.islice(stack, 1, None)
                        stack = reversed(list(stack))
                        
                        tb = 'Traceback (most recent call last):\n'
                        tb += ''.join(traceback.format_list(stack))
                        # replace AssertionError with ExpectationError
                        tb += 'ExpectationError: ' + str(e) + '\n'
                        self._expectations.append(tb)
                return wrapper
            except AttributeError:
                # do not raise for newname, but for name instead
                pass
        raise AttributeError("'%s' object has no attribute '%s'" % (self.__class__.__name__, name))

    #try:
    #except self.failureException as e: 
Example #25
Source File: YoutubeDL.py    From youtube-dl-GUI with MIT License 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 += encode_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 #26
Source File: exceptions.py    From neuralmonkey with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __str__(self) -> str:
        """Convert this exception to string."""

        trc = "".join(traceback.format_list(traceback.extract_tb(
            self.original_exception.__traceback__)))
        return "Error while loading '{}': {}\nTraceback: {}".format(
            self.object_name, self.original_exception, trc) 
Example #27
Source File: Errors.py    From royal-chaos with MIT License 5 votes vote down vote up
def __init__(self,msg='',ex=None):
		self.msg=msg
		assert not isinstance(msg,Exception)
		self.stack=[]
		if ex:
			if not msg:
				self.msg=str(ex)
			if isinstance(ex,WafError):
				self.stack=ex.stack
			else:
				self.stack=traceback.extract_tb(sys.exc_info()[2])
		self.stack+=traceback.extract_stack()[:-1]
		self.verbose_msg=''.join(traceback.format_list(self.stack)) 
Example #28
Source File: YoutubeDL.py    From tvalacarta with GNU General Public License v3.0 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 += encode_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 #29
Source File: config.py    From dragonfly with GNU Lesser General Public License v3.0 5 votes vote down vote up
def load_from_file(self, path):
        namespace = dict(self._sections)
        for name, section in self._sections_list:
            section.update_namespace(namespace)

        try:
            execfile(path, namespace)
#        except ConfigError, e:
        except Exception, e:
            print "exception:", e
            t, v, tb = sys.exc_info()
            frames = traceback.extract_tb(tb)
            relevant_frames = []
            error_line = "<unknown>"
            include_all = False
            for frame in frames:
                filename, line, function, text = frame
                print "frame:", frame

                if not include_all:
                    file1 = os.path.basename(filename)
                    file2 = os.path.basename(path)
                    if file1 == file2:
                        include_all = True
                        error_line = line

                if include_all:
                    relevant_frames.append(frame)

            self._log.error("An error occurred in the %s file at line %s."
                            % (path, error_line))
            self._log.error("The error message was: %s" % e)
            formatted = traceback.format_list(relevant_frames)
            lines = "\n".join(formatted).splitlines()
            for line in lines:
                self._log.error("    " + line) 
Example #30
Source File: warnings.py    From GraphicDesignPatternByPython with MIT License 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.