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: 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 #2
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 #3
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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
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 #15
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 #16
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 #17
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 #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: pp_module.py    From snoop with MIT License 5 votes vote down vote up
def write(self, source, value, depth=0):
        if depth == 0:
            value_string = pprint.pformat(value)
        else:
            try:
                value_string = repr(value)
            except Exception as e:
                exception_string = ''.join(
                    traceback.format_exception_only(type(e), e)
                ).strip()
                value_string = '<Exception in repr(): {}>'.format(exception_string)

        formatted = self.config.formatter.format_log_value(
            self.event, source, value_string, depth)
        self.config.write(formatted) 
Example #20
Source File: repr.py    From RSSNewsGAE 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 #21
Source File: tbtools.py    From RSSNewsGAE 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 rv.decode('utf-8', 'replace') if PY2 else rv 
Example #22
Source File: test_traceback.py    From BinderFilter with MIT License 5 votes vote down vote up
def test_unicode(self):
        err = AssertionError('\xff')
        lines = traceback.format_exception_only(type(err), err)
        self.assertEqual(lines, ['AssertionError: \xff\n'])

        err = AssertionError(u'\xe9')
        lines = traceback.format_exception_only(type(err), err)
        self.assertEqual(lines, ['AssertionError: \\xe9\n']) 
Example #23
Source File: commbase.py    From spyder-kernels with MIT License 5 votes vote down vote up
def format_error(self):
        """
        Format the error recieved from the other side and returns a list of
        strings.
        """
        lines = (['Exception in comms call {}:\n'.format(self.call_name)]
                 + traceback.format_list(self.tb)
                 + traceback.format_exception_only(self.etype, self.error))
        return lines 
Example #24
Source File: formatting.py    From snoop with MIT License 5 votes vote down vote up
def format_exception(self, event):
        lines = []
        exception_string = u''.join(traceback.format_exception_only(*event.arg[:2]))
        lines += [
            u'{c.red}!!! {line}{c.reset}'.format(
                c=self.c,
                line=line,
            )
            for line in exception_string.splitlines()
        ]
        lines += self.format_executing_node_exception(event)
        return lines 
Example #25
Source File: cgi.py    From ironpython2 with Apache License 2.0 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 #26
Source File: test_traceback.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def get_exception_format(self, func, exc):
        try:
            func()
        except exc, value:
            return traceback.format_exception_only(exc, value) 
Example #27
Source File: test_traceback.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_string_exception1(self):
        str_type = "String Exception"
        err = traceback.format_exception_only(str_type, None)
        self.assertEqual(len(err), 1)
        self.assertEqual(err[0], str_type + '\n') 
Example #28
Source File: test_traceback.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_string_exception2(self):
        str_type = "String Exception"
        str_value = "String Value"
        err = traceback.format_exception_only(str_type, str_value)
        self.assertEqual(len(err), 1)
        self.assertEqual(err[0], str_type + ': ' + str_value + '\n') 
Example #29
Source File: test_traceback.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_unicode(self):
        err = AssertionError('\xff')
        lines = traceback.format_exception_only(type(err), err)
        self.assertEqual(lines, ['AssertionError: \xff\n'])

        err = AssertionError(u'\xe9')
        lines = traceback.format_exception_only(type(err), err)
        self.assertEqual(lines, ['AssertionError: \\xe9\n']) 
Example #30
Source File: test_traceback.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_without_exception(self):
        err = traceback.format_exception_only(None, None)
        self.assertEqual(err, ['None\n'])