Python traceback.format_exception_only() Examples

The following are 30 code examples of traceback.format_exception_only(). 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: Exceptions.py    From rtp_cluster with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def dump_exception(msg, f = sys.stdout, extra = None):
    exc_type, exc_value, exc_traceback = sys.exc_info()
    if isinstance(exc_value, StdException):
        cus_traceback = exc_value.traceback
    else:
        if hasattr(exc_value, 'traceback'):
            exc_traceback = exc_value.traceback
        cus_traceback = None
    f.write('%s %s:\n' % (datetime.now(), msg))
    f.write(SEPT)
    if cus_traceback != None:
        f.write('Traceback (most recent call last):\n')
        print_list(cus_traceback, file = f)
        f.write(format_exception_only(exc_type, exc_value)[0])
    else:
        print_exception(exc_type, exc_value, exc_traceback, file = f)
    f.write(SEPT)
    if extra != None:
        f.write(extra)
        f.write(SEPT)
    f.flush() 
Example #2
Source File: error_monitor.py    From backend.ai-manager with GNU Lesser General Public License v3.0 6 votes vote down vote up
def capture_exception(self, exc: Optional[BaseException] = None, user: Any = None,
                                context_env: Any = None,
                                severity: Optional[LogSeverity] = None):
        if exc:
            tb = exc.__traceback__
        else:
            _, exc, tb = sys.exc_info()
        exc_type: Any = type(exc)
        if severity is None:
            severity = LogSeverity.ERROR
        async with self.dbpool.acquire() as conn, conn.begin():
            query = error_logs.insert().values({
                'severity': severity,
                'source': 'manager',
                'user': user,
                'message': ''.join(traceback.format_exception_only(exc_type, exc)).strip(),
                'context_lang': 'python',
                'context_env': context_env,
                'traceback': ''.join(traceback.format_tb(tb)).strip()
            })
            await conn.execute(query)
        log.debug('Manager log collected: {}', str(exc)) 
Example #3
Source File: materialized_views_test.py    From cassandra-dtest with Apache License 2.0 6 votes vote down vote up
def _do_row(self, insert_stmt, i, num_partitions):

        # Error callback for async requests
        def handle_errors(row, exc):
            self.num_request_done += 1
            try:
                name = type(exc).__name__
                self.exception_type[name] += 1
            except Exception as e:
                print(traceback.format_exception_only(type(e), e))

        # Success callback for async requests
        def success_callback(row):
            self.num_request_done += 1

        if i % self.update_stats_every == 0:
            self._print_write_status(i)

        row = row_generate(i, num_partitions)

        async_ret = self.session.execute_async(insert_stmt, row)
        errors = partial(handle_errors, row)
        async_ret.add_callbacks(success_callback, errors) 
Example #4
Source File: Console.py    From tf-pose with Apache License 2.0 6 votes vote down vote up
def exceptionHandler(self, excType, exc, tb, systrace=False):
        if self.ui.catchNextExceptionBtn.isChecked():
            self.ui.catchNextExceptionBtn.setChecked(False)
        elif not self.ui.catchAllExceptionsBtn.isChecked():
            return
        
        self.currentTraceback = tb
        
        excMessage = ''.join(traceback.format_exception_only(excType, exc))
        self.ui.exceptionInfoLabel.setText(excMessage)

        if systrace:
            # exceptions caught using systrace don't need the usual 
            # call stack + traceback handling
            self.setStack(sys._getframe().f_back.f_back)
        else:
            self.setStack(frame=sys._getframe().f_back, tb=tb) 
Example #5
Source File: pdbpp.py    From pdbpp with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def do_pp(self, arg):
        """[width]pp expression
        Pretty-print the value of the expression.
        """
        width = getattr(arg, "cmd_count", None)
        try:
            val = self._getval(arg)
        except:
            return
        if width is None:
            try:
                width, _ = self.get_terminal_size()
            except Exception as exc:
                self.message("warning: could not get terminal size ({})".format(exc))
                width = None
        try:
            pprint.pprint(val, self.stdout, width=width)
        except:
            exc_info = sys.exc_info()[:2]
            self.error(traceback.format_exception_only(*exc_info)[-1].strip()) 
Example #6
Source File: utils.py    From sacred with MIT License 6 votes vote down vote up
def filtered_traceback_format(tb_exception, chain=True):
    if chain:
        if tb_exception.__cause__ is not None:
            yield from filtered_traceback_format(tb_exception.__cause__, chain=chain)
            yield tb._cause_message
        elif (
            tb_exception.__context__ is not None
            and not tb_exception.__suppress_context__
        ):
            yield from filtered_traceback_format(tb_exception.__context__, chain=chain)
            yield tb._context_message
    yield "Traceback (most recent calls WITHOUT Sacred internals):\n"
    current_tb = tb_exception.exc_traceback
    while current_tb is not None:
        if not _is_sacred_frame(current_tb.tb_frame):
            stack = tb.StackSummary.extract(
                tb.walk_tb(current_tb), limit=1, lookup_lines=True, capture_locals=False
            )
            yield from stack.format()
        current_tb = current_tb.tb_next
    yield from tb_exception.format_exception_only()


# noinspection PyUnusedLocal 
Example #7
Source File: evaluate.py    From python-netsurv with MIT License 6 votes vote down vote up
def istrue(self):
        try:
            return self._istrue()
        except TEST_OUTCOME:
            self.exc = sys.exc_info()
            if isinstance(self.exc[1], SyntaxError):
                msg = [" " * (self.exc[1].offset + 4) + "^"]
                msg.append("SyntaxError: invalid syntax")
            else:
                msg = traceback.format_exception_only(*self.exc[:2])
            fail(
                "Error evaluating %r expression\n"
                "    %s\n"
                "%s" % (self._mark_name, self.expr, "\n".join(msg)),
                pytrace=False,
            ) 
Example #8
Source File: evaluate.py    From python-netsurv with MIT License 6 votes vote down vote up
def istrue(self):
        try:
            return self._istrue()
        except TEST_OUTCOME:
            self.exc = sys.exc_info()
            if isinstance(self.exc[1], SyntaxError):
                msg = [" " * (self.exc[1].offset + 4) + "^"]
                msg.append("SyntaxError: invalid syntax")
            else:
                msg = traceback.format_exception_only(*self.exc[:2])
            fail(
                "Error evaluating %r expression\n"
                "    %s\n"
                "%s" % (self._mark_name, self.expr, "\n".join(msg)),
                pytrace=False,
            ) 
Example #9
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 #10
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 #11
Source File: expressions.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def Start(self, callback):
        try:
            try:
                try:
                    self.result = eval(self.code, self.frame.f_globals, self.frame.f_locals)
                except SyntaxError:
                    exec self.code in self.frame.f_globals, self.frame.f_locals
                    self.result = ""
                self.hresult = 0
            except:
                l = traceback.format_exception_only(sys.exc_info()[0], sys.exc_info()[1])
                # l is a list of strings with trailing "\n"
                self.result = string.join(map(lambda s:s[:-1], l), "\n")
                self.hresult = winerror.E_FAIL
        finally:
            self.isComplete = 1
            callback.onComplete() 
Example #12
Source File: test_traceback.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_base_exception(self):
        # Test that exceptions derived from BaseException are formatted right
        e = KeyboardInterrupt()
        lst = traceback.format_exception_only(e.__class__, e)
        self.assertEqual(lst, ['KeyboardInterrupt\n'])

    # String exceptions are deprecated, but legal.  The quirky form with
    # separate "type" and "value" tends to break things, because
    #     not isinstance(value, type)
    # and a string cannot be the first argument to issubclass.
    #
    # Note that sys.last_type and sys.last_value do not get set if an
    # exception is caught, so we sort of cheat and just emulate them.
    #
    # test_string_exception1 is equivalent to
    #
    # >>> raise "String Exception"
    #
    # test_string_exception2 is equivalent to
    #
    # >>> raise "String Exception", "String Value"
    # 
Example #13
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 #14
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 #15
Source File: px.py    From px with MIT License 6 votes vote down vote up
def handle_exceptions(extype, value, tb):
    # Create traceback log
    lst = (traceback.format_tb(tb, None) +
        traceback.format_exception_only(extype, value))
    tracelog = '\nTraceback (most recent call last):\n' + "%-20s%s\n" % (
        "".join(lst[:-1]), lst[-1])

    if State.logger != None:
        pprint(tracelog)
    else:
        sys.stderr.write(tracelog)

        # Save to debug.log
        dbg = open(dfile(), 'w')
        dbg.write(tracelog)
        dbg.close()

###
# Install Px to startup 
Example #16
Source File: errors.py    From kotori with GNU Affero General Public License v3.0 6 votes vote down vote up
def traceback_get_exception(num = -1):

    # build error message
    exception_string = ''.join(traceback.format_exception_only(sys.exc_type, hasattr(sys, 'exc_value') and sys.exc_value or 'Unknown'))

    # extract error location from traceback
    if hasattr(sys, 'exc_traceback'):
        (filename, line_number, function_name, text) = traceback.extract_tb(sys.exc_traceback)[num]
    else:
        (filename, line_number, function_name, text) = ('-', '-', '-', '-')

    error = {
        'message': exception_string,
        'location': {
            'filename': filename,
            'line_number': line_number,
            'function_name': function_name,
            'text': text,
            }
    }

    return error 
Example #17
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 #18
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 #19
Source File: cgi.py    From jawfish with MIT License 5 votes vote down vote up
def print_exception(type=None, value=None, tb=None, limit=None):
    if type is None:
        type, value, tb = sys.exc_info()
    import traceback
    print
    print "<H3>Traceback (most recent call last):</H3>"
    list = traceback.format_tb(tb, limit) + \
           traceback.format_exception_only(type, value)
    print "<PRE>%s<B>%s</B></PRE>" % (
        escape("".join(list[:-1])),
        escape(list[-1]),
        )
    del tb 
Example #20
Source File: cgi.py    From jawfish with MIT License 5 votes vote down vote up
def print_exception(type=None, value=None, tb=None, limit=None):
    if type is None:
        type, value, tb = sys.exc_info()
    import traceback
    print
    print "<H3>Traceback (most recent call last):</H3>"
    list = traceback.format_tb(tb, limit) + \
           traceback.format_exception_only(type, value)
    print "<PRE>%s<B>%s</B></PRE>" % (
        escape("".join(list[:-1])),
        escape(list[-1]),
        )
    del tb 
Example #21
Source File: doctest_driver.py    From razzy-spinner with GNU General Public License v3.0 5 votes vote down vote up
def _check_exception(self, example):
        want_exc_msg = example.exc_msg
        optionflags = self._get_optionflags(example)
        exc_info = sys.exc_info()
        got_exc_msg = traceback.format_exception_only(*exc_info[:2])[-1]
        if not self.checker.check_output(want_exc_msg, got_exc_msg,
                                         optionflags):
            got = _exception_traceback(exc_info)
            self.runner.report_failure(self.save_stdout.write,
                                       self.test, example, got)
            return False
        else:
            return True 
Example #22
Source File: test_runner.py    From Zopkio with Apache License 2.0 5 votes vote down vote up
def _log_results(self, tests):
    for test in tests:
      logger.info("{0}----{1}".format(test.name, test.result))
      if test.result == constants.PASSED:
        self._success_count += 1
      else:
        logger.info(traceback.format_exception_only(type(test.exception), test.exception))
        self._failed_count += 1 
Example #23
Source File: code.py    From py with MIT License 5 votes vote down vote up
def exconly(self, tryshort=False):
        """ return the exception as a string

            when 'tryshort' resolves to True, and the exception is a
            py.code._AssertionError, only the actual exception part of
            the exception representation is returned (so 'AssertionError: ' is
            removed from the beginning)
        """
        lines = format_exception_only(self.type, self.value)
        text = ''.join(lines)
        text = text.rstrip()
        if tryshort:
            if text.startswith(self._striptext):
                text = text[len(self._striptext):]
        return text 
Example #24
Source File: crashdialog.py    From qutebrowser with GNU General Public License v3.0 5 votes vote down vote up
def _get_paste_title_desc(self):
        desc = traceback.format_exception_only(self._exc[0], self._exc[1])
        return desc[0].rstrip() 
Example #25
Source File: repr.py    From recruit with Apache License 2.0 5 votes vote down vote up
def fallback_repr(self):
        try:
            info = "".join(format_exception_only(*sys.exc_info()[:2]))
        except Exception:  # pragma: no cover
            info = "?"
        if PY2:
            info = info.decode("utf-8", "ignore")
        return u'<span class="brokenrepr">&lt;broken repr (%s)&gt;' u"</span>" % escape(
            info.strip()
        ) 
Example #26
Source File: tbtools.py    From recruit with Apache License 2.0 5 votes vote down vote up
def exception(self):
        """String representation of the exception."""
        buf = traceback.format_exception_only(self.exc_type, self.exc_value)
        rv = "".join(buf).strip()
        return to_unicode(rv, "utf-8", "replace") 
Example #27
Source File: utils.py    From schemathesis with MIT License 5 votes vote down vote up
def format_exception(error: Exception, include_traceback: bool = False) -> str:
    if include_traceback:
        return "".join(traceback.format_exception(type(error), error, error.__traceback__))
    return "".join(traceback.format_exception_only(type(error), error)) 
Example #28
Source File: repr.py    From jbox with MIT License 5 votes vote down vote up
def fallback_repr(self):
        try:
            info = ''.join(format_exception_only(*sys.exc_info()[:2]))
        except Exception:  # pragma: no cover
            info = '?'
        if PY2:
            info = info.decode('utf-8', 'ignore')
        return u'<span class="brokenrepr">&lt;broken repr (%s)&gt;' \
               u'</span>' % escape(info.strip()) 
Example #29
Source File: tbtools.py    From jbox with MIT License 5 votes vote down vote up
def exception(self):
        """String representation of the exception."""
        buf = traceback.format_exception_only(self.exc_type, self.exc_value)
        rv = ''.join(buf).strip()
        return rv.decode('utf-8', 'replace') if PY2 else rv 
Example #30
Source File: collector.py    From mishkal with GNU General Public License v3.0 5 votes vote down vote up
def collectExceptionOnly(self, etype, value):
        return traceback.format_exception_only(etype, value)