Python traceback.format_tb() Examples

The following are code examples for showing how to use traceback.format_tb(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the ones you don't like. You can also save this page to your account.

Example 1
Project: django-performance-testing   Author: PaesslerAG   File: core.py    (BSD 3-Clause "New" or "Revised" License) View Source Project 6 votes vote down vote up
def __exit__(self, exc_type, exc_val, exc_tb):
        self.before_exit()
        signal_responses = results_collected.send_robust(
            sender=self, results=self.get_results_to_send(),
            context=copy.deepcopy(context.current.data))
        if exc_type is None:
            for (receiver, response) in signal_responses:
                if isinstance(response,  BaseException):
                    orig_tb = ''.join(
                        traceback.format_tb(response.__traceback__))
                    error_msg = '{}{}: {}'.format(
                        orig_tb,
                        type(response).__name__,
                        str(response)
                    )
                    if hasattr(response, 'clone_with_more_info'):
                        new_exc = response.clone_with_more_info(
                            orig_tb=orig_tb)
                    else:
                        new_exc = type(response)(error_msg)
                    raise new_exc 
Example 2
Project: mongodb-monitoring   Author: jruaux   File: search_command.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def _report_unexpected_error(self):

        error_type, error, tb = sys.exc_info()
        origin = tb

        while origin.tb_next is not None:
            origin = origin.tb_next

        filename = origin.tb_frame.f_code.co_filename
        lineno = origin.tb_lineno
        message = '{0} at "{1}", line {2:d} : {3}'.format(error_type.__name__, filename, lineno, error)

        environment.splunklib_logger.error(message + '\nTraceback:\n' + ''.join(traceback.format_tb(tb)))
        self.write_error(message)

    # endregion

    # region Types 
Example 3
Project: Splunk_CBER_App   Author: MHaggis   File: search_command.py    (license) View Source Project 6 votes vote down vote up
def _report_unexpected_error(self):

        error_type, error, tb = sys.exc_info()
        origin = tb

        while origin.tb_next is not None:
            origin = origin.tb_next

        filename = origin.tb_frame.f_code.co_filename
        lineno = origin.tb_lineno
        message = '{0} at "{1}", line {2:d} : {3}'.format(error_type.__name__, filename, lineno, error)

        environment.splunklib_logger.error(message + '\nTraceback:\n' + ''.join(traceback.format_tb(tb)))
        self.write_error(message)

    # endregion

    # region Types 
Example 4
Project: xmpp-cloud-auth   Author: jsxc   File: roster_thread.py    (license) View Source Project 6 votes vote down vote up
def roster_background_thread(self, sr):
        '''Entry for background roster update thread'''
        try:
            logging.debug('roster_thread for ' + str(sr))
            # Allow test hooks with static ejabberd_controller
            if hasattr(self.ctx, 'ejabberd_controller') and self.ctx.ejabberd_controller is not None:
                e = self.ctx.ejabberd_controller
            else:
                e = ejabberdctl(self.ctx)
            groups, commands = self.roster_update_users(e, sr)
            self.roster_update_groups(e, groups)
            # For some reason, the vcard changes are not pushed to the clients. Rinse and repeat.
# Maybe not necessary with synchronous thread?
#            for cmd in commands:
#                e.execute(cmd)
            self.ctx.shared_roster_db.sync()
        except AttributeError:
            pass # For tests
        except Exception, err:
            (etype, value, tb) = sys.exc_info()
            traceback.print_exception(etype, value, tb)
            logging.warn('roster_groups thread: %s:\n%s'
                         % (str(err), ''.join(traceback.format_tb(tb))))
            return False 
Example 5
Project: hostapd-mana   Author: adde88   File: pyversion.py    (license) View Source Project 6 votes vote down vote up
def format_exception(exc_info, encoding='UTF-8'):
    ec, ev, tb = exc_info

    # Our exception object may have been turned into a string, and Python 3's
    # traceback.format_exception() doesn't take kindly to that (it expects an
    # actual exception object).  So we work around it, by doing the work
    # ourselves if ev is not an exception object.
    if not is_base_exception(ev):
        tb_data = force_unicode(
                ''.join(traceback.format_tb(tb)),
                encoding)
        ev = exc_to_unicode(ev)
        return tb_data + ev
    else:
        return force_unicode(
                ''.join(traceback.format_exception(*exc_info)),
                encoding) 
Example 6
Project: hostapd-mana   Author: adde88   File: cgi.py    (license) View Source Project 6 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 7
Project: pytest-random-order   Author: jbasko   File: plugin.py    (license) View Source Project 6 votes vote down vote up
def pytest_collection_modifyitems(session, config, items):
    failure = None

    item_ids = _get_set_of_item_ids(items)

    try:
        seed = getattr(config, 'random_order_seed', None)
        bucket_type = config.getoption('random_order_bucket')
        _shuffle_items(items, bucket_key=_random_order_item_keys[bucket_type], disable=_disable, seed=seed)

    except Exception as e:
        # See the finally block -- we only fail if we have lost user's tests.
        _, _, exc_tb = sys.exc_info()
        failure = 'pytest-random-order plugin has failed with {0!r}:\n{1}'.format(
            e, ''.join(traceback.format_tb(exc_tb, 10))
        )
        config.warn(0, failure, None)

    finally:
        # Fail only if we have lost user's tests
        if item_ids != _get_set_of_item_ids(items):
            if not failure:
                failure = 'pytest-random-order plugin has failed miserably'
            raise RuntimeError(failure) 
Example 8
Project: qcore   Author: quora   File: test_errors.py    (license) View Source Project 6 votes vote down vote up
def test_errors():
    def f1():
        assert 0, 'holy moly'

    def raise_later(e):
        errors.reraise(e)

    def f2():
        try:
            f1()
        except AssertionError as e:
            prepared_e = errors.prepare_for_reraise(e)
        else:
            assert False, 'f1 should have raised AssertionError'
        raise_later(prepared_e)

    try:
        f2()
    except AssertionError:
        formatted = traceback.format_tb(sys.exc_info()[2])
        formatted_message = ''.join(formatted)
        assert_in('holy moly', formatted_message)
        assert_in('f1', formatted_message)
    else:
        assert False, 'f2 should have raised AssertionError' 
Example 9
Project: SSURGO-QA   Author: ncss-tech   File: GenerateSpecialFeatures.py    (license) View Source Project 6 votes vote down vote up
def errorMsg():

    try:

        tb = sys.exc_info()[2]
        tbinfo = traceback.format_tb(tb)[0]
        theMsg = tbinfo + " \n" + str(sys.exc_type)+ ": " + str(sys.exc_value) + " \n"
        arcMsg = "ArcPy ERRORS:\n" + arcpy.GetMessages(2) + "\n"
        PrintMsg(theMsg, 2)
        PrintMsg(arcMsg, 2)

    except:

        PrintMsg("Unhandled error in errorMsg method", 2)

#====================================================================================================================================== 
Example 10
Project: zippy   Author: securesystemslab   File: test_traceback.py    (license) View Source Project 6 votes vote down vote up
def test_traceback_format(self):
        try:
            raise KeyError('blah')
        except KeyError:
            type_, value, tb = sys.exc_info()
            traceback_fmt = 'Traceback (most recent call last):\n' + \
                            ''.join(traceback.format_tb(tb))
            file_ = StringIO()
            _testcapi.traceback_print(tb, file_)
            python_fmt  = file_.getvalue()
        else:
            raise Error("unable to create test traceback string")

        # Make sure that Python and the traceback module format the same thing
        self.assertEqual(traceback_fmt, python_fmt)

        # Make sure that the traceback is properly indented.
        tb_lines = python_fmt.splitlines()
        self.assertEqual(len(tb_lines), 3)
        banner, location, source_line = tb_lines
        self.assertTrue(banner.startswith('Traceback'))
        self.assertTrue(location.startswith('  File'))
        self.assertTrue(source_line.startswith('    raise')) 
Example 11
Project: zippy   Author: securesystemslab   File: test_exceptions.py    (license) View Source Project 6 votes vote down vote up
def test_MemoryError(self):
        # PyErr_NoMemory always raises the same exception instance.
        # Check that the traceback is not doubled.
        import traceback
        from _testcapi import raise_memoryerror
        def raiseMemError():
            try:
                raise_memoryerror()
            except MemoryError as e:
                tb = e.__traceback__
            else:
                self.fail("Should have raises a MemoryError")
            return traceback.format_tb(tb)

        tb1 = raiseMemError()
        tb2 = raiseMemError()
        self.assertEqual(tb1, tb2) 
Example 12
Project: steemvote   Author: Kefkius   File: main_window.py    (license) View Source Project 6 votes vote down vote up
def timer_actions(self):
        now = time.time()
        try:
            # voter will update via RPC once every interval.
            self.voter.update()

            if now - self.last_vote > self.vote_interval:
                self.last_vote = now
                self.voter.vote_for_comments()
        except Exception as e:
            self.logger.error(str(e))
            self.logger.error(''.join(traceback.format_tb(sys.exc_info()[2])))

        # Update tracked comments.
        tracked_comments = set(self.voter.db.tracked_comments.values())
        if self.last_tracked_comments != tracked_comments:
            self.comments_widget.update_comments()
            self.last_tracked_comments = tracked_comments

        self.voting_power_label.setText('Voting power: %s' % self.voter.get_voting_power()) 
Example 13
Project: chihu   Author: yelongyu   File: base.py    (license) View Source Project 6 votes vote down vote up
def load_wsgi(self):
        try:
            self.wsgi = self.app.wsgi()
        except SyntaxError as e:
            if not self.cfg.reload:
                raise

            self.log.exception(e)

            # fix from PR #1228
            # storing the traceback into exc_tb will create a circular reference.
            # per https://docs.python.org/2/library/sys.html#sys.exc_info warning,
            # delete the traceback after use.
            try:
                exc_type, exc_val, exc_tb = sys.exc_info()
                self.reloader.add_extra_file(exc_val.filename)

                tb_string = traceback.format_tb(exc_tb)
                self.wsgi = util.make_fail_app(tb_string)
            finally:
                del exc_tb 
Example 14
Project: super_simple_siem   Author: elucidant   File: search_command.py    (license) View Source Project 6 votes vote down vote up
def _report_unexpected_error(self):

        error_type, error, tb = sys.exc_info()
        origin = tb

        while origin.tb_next is not None:
            origin = origin.tb_next

        filename = origin.tb_frame.f_code.co_filename
        lineno = origin.tb_lineno
        message = '{0} at "{1}", line {2:d} : {3}'.format(error_type.__name__, filename, lineno, error)

        environment.splunklib_logger.error(message + '\nTraceback:\n' + ''.join(traceback.format_tb(tb)))
        self.write_error(message)

    # endregion

    # region Types 
Example 15
Project: fandango   Author: tango-controls   File: excepts.py    (license) View Source Project 6 votes vote down vote up
def getPreviousExceptions(limit=0):
    """
    sys.exc_info() returns : type,value,traceback
    traceback.extract_tb(traceback) :  returns (filename, line number, function name, text)
    """
    try:
        exinfo = sys.exc_info()
        if exinfo[0] is not None:
            stack = traceback.format_tb(exinfo[2])
            return str('\n'.join(['Tracebacks (most recent call last):',
                                ''.join(stack[(len(stack)>1 and 1 or 0):]),
                                ': '.join([str(exinfo[0].__name__),str(exinfo[1])])
                                ]))
        else:
            return ''
    except Exception,e:
        print 'Aaaargh!'
        return traceback.format_exc() 
Example 16
Project: oil   Author: oilshell   File: test_traceback.py    (license) View Source Project 6 votes vote down vote up
def test_traceback_format(self):
        from _testcapi import traceback_print
        try:
            raise KeyError('blah')
        except KeyError:
            type_, value, tb = sys.exc_info()
            traceback_fmt = 'Traceback (most recent call last):\n' + \
                            ''.join(traceback.format_tb(tb))
            file_ = StringIO()
            traceback_print(tb, file_)
            python_fmt  = file_.getvalue()
        else:
            raise Error("unable to create test traceback string")

        # Make sure that Python and the traceback module format the same thing
        self.assertEqual(traceback_fmt, python_fmt)

        # Make sure that the traceback is properly indented.
        tb_lines = python_fmt.splitlines()
        self.assertEqual(len(tb_lines), 3)
        banner, location, source_line = tb_lines
        self.assertTrue(banner.startswith('Traceback'))
        self.assertTrue(location.startswith('  File'))
        self.assertTrue(source_line.startswith('    raise')) 
Example 17
Project: python2-tracer   Author: extremecoders-re   File: test_traceback.py    (license) View Source Project 6 votes vote down vote up
def test_traceback_format(self):
        from _testcapi import traceback_print
        try:
            raise KeyError('blah')
        except KeyError:
            type_, value, tb = sys.exc_info()
            traceback_fmt = 'Traceback (most recent call last):\n' + \
                            ''.join(traceback.format_tb(tb))
            file_ = StringIO()
            traceback_print(tb, file_)
            python_fmt  = file_.getvalue()
        else:
            raise Error("unable to create test traceback string")

        # Make sure that Python and the traceback module format the same thing
        self.assertEqual(traceback_fmt, python_fmt)

        # Make sure that the traceback is properly indented.
        tb_lines = python_fmt.splitlines()
        self.assertEqual(len(tb_lines), 3)
        banner, location, source_line = tb_lines
        self.assertTrue(banner.startswith('Traceback'))
        self.assertTrue(location.startswith('  File'))
        self.assertTrue(source_line.startswith('    raise')) 
Example 18
Project: tabmaster   Author: NicolasMinghetti   File: base.py    (license) View Source Project 6 votes vote down vote up
def load_wsgi(self):
        try:
            self.wsgi = self.app.wsgi()
        except SyntaxError as e:
            if not self.cfg.reload:
                raise

            self.log.exception(e)

            # fix from PR #1228
            # storing the traceback into exc_tb will create a circular reference.
            # per https://docs.python.org/2/library/sys.html#sys.exc_info warning,
            # delete the traceback after use.
            try:
                exc_type, exc_val, exc_tb = sys.exc_info()
                self.reloader.add_extra_file(exc_val.filename)

                tb_string = traceback.format_tb(exc_tb)
                self.wsgi = util.make_fail_app(tb_string)
            finally:
                del exc_tb 
Example 19
Project: sslstrip-hsts-openwrt   Author: adde88   File: pyversion.py    (license) View Source Project 6 votes vote down vote up
def format_exception(exc_info, encoding='UTF-8'):
    ec, ev, tb = exc_info

    # Our exception object may have been turned into a string, and Python 3's
    # traceback.format_exception() doesn't take kindly to that (it expects an
    # actual exception object).  So we work around it, by doing the work
    # ourselves if ev is not an exception object.
    if not is_base_exception(ev):
        tb_data = force_unicode(
                ''.join(traceback.format_tb(tb)),
                encoding)
        ev = exc_to_unicode(ev)
        return tb_data + ev
    else:
        return force_unicode(
                ''.join(traceback.format_exception(*exc_info)),
                encoding) 
Example 20
Project: TA-connectivity   Author: seunomosowon   File: search_command.py    (license) View Source Project 6 votes vote down vote up
def _report_unexpected_error(self):

        error_type, error, tb = sys.exc_info()
        origin = tb

        while origin.tb_next is not None:
            origin = origin.tb_next

        filename = origin.tb_frame.f_code.co_filename
        lineno = origin.tb_lineno
        message = '{0} at "{1}", line {2:d} : {3}'.format(error_type.__name__, filename, lineno, error)

        environment.splunklib_logger.error(message + '\nTraceback:\n' + ''.join(traceback.format_tb(tb)))
        self.write_error(message)

    # endregion

    # region Types 
Example 21
Project: aiolocust   Author: kpidata   File: test_web.py    (license) View Source Project 6 votes vote down vote up
def test_exceptions_csv(self):
        try:
            raise Exception("Test exception")
        except Exception as e:
            tb = sys.exc_info()[2]
            runners.locust_runner.log_exception("local", str(e), "".join(traceback.format_tb(tb)))
            runners.locust_runner.log_exception("local", str(e), "".join(traceback.format_tb(tb)))
        
        response = requests.get("http://127.0.0.1:%i/exceptions/csv" % self.web_port)
        self.assertEqual(200, response.status_code)
        
        reader = csv.reader(StringIO(response.text))
        rows = []
        for row in reader:
            rows.append(row)
        
        self.assertEqual(2, len(rows))
        self.assertEqual("Test exception", rows[1][1])
        self.assertEqual(2, int(rows[1][0]), "Exception count should be 2") 
Example 22
Project: web_ctp   Author: molebot   File: test_traceback.py    (license) View Source Project 6 votes vote down vote up
def test_traceback_format(self):
        try:
            raise KeyError('blah')
        except KeyError:
            type_, value, tb = sys.exc_info()
            traceback_fmt = 'Traceback (most recent call last):\n' + \
                            ''.join(traceback.format_tb(tb))
            file_ = StringIO()
            traceback_print(tb, file_)
            python_fmt  = file_.getvalue()
        else:
            raise Error("unable to create test traceback string")

        # Make sure that Python and the traceback module format the same thing
        self.assertEqual(traceback_fmt, python_fmt)

        # Make sure that the traceback is properly indented.
        tb_lines = python_fmt.splitlines()
        self.assertEqual(len(tb_lines), 3)
        banner, location, source_line = tb_lines
        self.assertTrue(banner.startswith('Traceback'))
        self.assertTrue(location.startswith('  File'))
        self.assertTrue(source_line.startswith('    raise')) 
Example 23
Project: web_ctp   Author: molebot   File: test_exceptions.py    (license) View Source Project 6 votes vote down vote up
def test_MemoryError(self):
        # PyErr_NoMemory always raises the same exception instance.
        # Check that the traceback is not doubled.
        import traceback
        from _testcapi import raise_memoryerror
        def raiseMemError():
            try:
                raise_memoryerror()
            except MemoryError as e:
                tb = e.__traceback__
            else:
                self.fail("Should have raises a MemoryError")
            return traceback.format_tb(tb)

        tb1 = raiseMemError()
        tb2 = raiseMemError()
        self.assertEqual(tb1, tb2) 
Example 24
Project: python-   Author: secondtonone1   File: retrying.py    (license) View Source Project 5 votes vote down vote up
def __repr__(self):
        if self.has_exception:
            return "Attempts: {0}, Error:\n{1}".format(self.attempt_number, "".join(traceback.format_tb(self.value[2])))
        else:
            return "Attempts: {0}, Value: {1}".format(self.attempt_number, self.value) 
Example 25
Project: my-first-blog   Author: AnkurBegining   File: retrying.py    (license) View Source Project 5 votes vote down vote up
def __repr__(self):
        if self.has_exception:
            return "Attempts: {0}, Error:\n{1}".format(self.attempt_number, "".join(traceback.format_tb(self.value[2])))
        else:
            return "Attempts: {0}, Value: {1}".format(self.attempt_number, self.value) 
Example 26
Project: core-framework   Author: RedhawkSDR   File: properties.py    (license) View Source Project 5 votes vote down vote up
def query(self, obj, operator=None):
        # Get the complete current value via the base class interface.
        value = self._query(obj)
        if value is None:
            return any.to_any(value)

        # Don't apply an operator if the value is already a CORBA Any, which
        # should only occur in the case of a (legacy) user callback.
        if isinstance(value, CORBA.Any):
            return value

        # Attempt to apply the operator to the returned value.
        try:
            if operator in ("[]", "[*]"):
                value = self._getDefaultOperator(value, operator)
            elif operator == "[?]":
                value = self._getKeysOperator(value, operator)
                return any.to_any(check_type_for_long(value))
            elif operator == "[@]":
                value = self._getKeyValuePairsOperator(value, operator)
                return any.to_any(check_type_for_long(value))
            elif operator == "[#]":
                value = len(self._getDefaultOperator(value, operator))
                return any.to_any(check_type_for_long(value))
            elif operator != None:
                value = self._getSliceOperator(value, operator)
        except Exception, e:
            raise AttributeError, "error processing operator '%s': '%s' %s" % (operator, e, "\n".join(traceback.format_tb(sys.exc_traceback)))

        # At this point, value must be a normal sequence, so we can use the
        # standard conversion routine.
        return self._toAny(value) 
Example 27
Project: kinect-2-libras   Author: inessadl   File: cgi.py    (Apache License 2.0) View Source Project 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 28
Project: deb-python-retrying   Author: openstack   File: retrying.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def __repr__(self):
        if self.has_exception:
            return "Attempts: {0}, Error:\n{1}".format(self.attempt_number, "".join(traceback.format_tb(self.value[2])))
        else:
            return "Attempts: {0}, Value: {1}".format(self.attempt_number, self.value) 
Example 29
Project: mongodb-monitoring   Author: jruaux   File: external_search_command.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def execute(self):
        # noinspection PyBroadException
        try:
            if self._argv is None:
                self._argv = os.path.splitext(os.path.basename(self._path))[0]
            self._execute(self._path, self._argv, self._environ)
        except:
            error_type, error, tb = sys.exc_info()
            message = 'Command execution failed: ' + unicode(error)
            self._logger.error(message + '\nTraceback:\n' + ''.join(traceback.format_tb(tb)))
            sys.exit(1) 
Example 30
Project: pip-update-requirements   Author: alanhamlett   File: retrying.py    (BSD 2-Clause "Simplified" License) View Source Project 5 votes vote down vote up
def __repr__(self):
        if self.has_exception:
            return "Attempts: {0}, Error:\n{1}".format(self.attempt_number, "".join(traceback.format_tb(self.value[2])))
        else:
            return "Attempts: {0}, Value: {1}".format(self.attempt_number, self.value) 
Example 31
Project: code   Author: ActiveState   File: recipe-499333.py    (MIT License) View Source Project 5 votes vote down vote up
def main_function(getOptString='', numArgs=0):
    def main_decorator(maincode):
        def decorated_main(argv=[__name__]):
            try:
                opts={}
                args=[]
                if len(getOptString) > 0:
                    try:
                        opt_list, args = getopt.getopt(argv[1:], getOptString)
                        opts=dict([(x[0][1:], x[1]) for x in opt_list])
                    except getopt.error, msg:
                        raise Usage(msg)
                else:
                    args=argv[1:]
                if len(args) < numArgs:
                    raise Usage("Not enough arguments")
                return maincode(args, opts) or 0
            except KeyboardInterrupt:
                sys.exit(-1)
            except SystemExit:
                pass
            except Usage, usage:
                sys.stderr.write('%s\n%s\n' % (maincode.__doc__, usage.msg))
            except Exception, err:
                cla, exc, trbk = sys.exc_info()
                import traceback
                sys.stderr.write("Caught Exception:\n%s:%s\n%s" % (cla.__name__, str(exc), ''.join(traceback.format_tb(trbk,5))))
                sys.exit(-1)
        return decorated_main
    return main_decorator

########### Example Usage ################ 
Example 32
Project: Splunk_CBER_App   Author: MHaggis   File: external_search_command.py    (license) View Source Project 5 votes vote down vote up
def execute(self):
        # noinspection PyBroadException
        try:
            if self._argv is None:
                self._argv = os.path.splitext(os.path.basename(self._path))[0]
            self._execute(self._path, self._argv, self._environ)
        except:
            error_type, error, tb = sys.exc_info()
            message = 'Command execution failed: ' + unicode(error)
            self._logger.error(message + '\nTraceback:\n' + ''.join(traceback.format_tb(tb)))
            sys.exit(1) 
Example 33
Project: girder_worker   Author: girder   File: app.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def gw_task_failure(sender=None, exception=None,
                    traceback=None, **rest):
    try:

        msg = '%s: %s\n%s' % (
            exception.__class__.__name__, exception,
            ''.join(tb.format_tb(traceback)))

        sender.job_manager.write(msg)

        _update_status(sender, JobStatus.ERROR)
    except AttributeError:
        pass 
Example 34
Project: dash-pi   Author: andrewvaughan   File: __main__.py    (MIT License) View Source Project 5 votes vote down vote up
def handle_exception(ex_cls, ex, trace):
        """Catches all errors and sends them through the logger"""

        LOGGER.critical("EXCEPTION")
        LOGGER.critical(''.join(traceback.format_tb(trace)))
        LOGGER.critical('%s: %s', ex_cls, ex) 
Example 35
Project: swjtu-pyscraper   Author: Desgard   File: retrying.py    (MIT License) View Source Project 5 votes vote down vote up
def __repr__(self):
        if self.has_exception:
            return "Attempts: {0}, Error:\n{1}".format(self.attempt_number, "".join(traceback.format_tb(self.value[2])))
        else:
            return "Attempts: {0}, Value: {1}".format(self.attempt_number, self.value) 
Example 36
Project: jenkins-epo   Author: peopledoc   File: script.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def entrypoint(argv=None):
    argv = argv or sys.argv[1:]

    logging.config.dictConfig(setup_logging())
    distribution = pkg_resources.get_distribution('jenkins-epo')
    logger.info("Starting jenkins-epo %s.", distribution.version)
    logger.debug("Debug mode enabled")

    # Import modules after logging is setup
    from .cache import CACHE
    from .main import main
    from .settings import SETTINGS

    try:
        logger.debug("Executing %s.", ' '.join(argv))
        main(argv)
        logger.info("Done.")
    except bdb.BdbQuit:
        logger.info('Graceful exit from debugger.')
    except Exception as e:
        if SETTINGS.DEBUG:
            logger.error("%s: %s", type(e), e)
            post_mortem()
        else:
            logger.exception("Unhandled error:")
        sys.exit(1)
    except KeyboardInterrupt:
        # Hide ^C in terminal
        sys.stderr.write('\r')
        if SETTINGS.DEBUG:
            logger.warn("Dropping in post interrupt PDB!")
            post_mortem()
        else:
            tb = traceback.format_tb(sys.exc_info()[-1])
            tb = tb[-6:]
            logger.warn("Interrupted at:\n%s", ''.join(tb).strip())
        sys.exit(1)
    finally:
        CACHE.close()

    sys.exit(0) 
Example 37
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: retrying.py    (MIT License) View Source Project 5 votes vote down vote up
def __repr__(self):
        if self.has_exception:
            return "Attempts: {0}, Error:\n{1}".format(self.attempt_number, "".join(traceback.format_tb(self.value[2])))
        else:
            return "Attempts: {0}, Value: {1}".format(self.attempt_number, self.value) 
Example 38
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: retrying.py    (MIT License) View Source Project 5 votes vote down vote up
def __repr__(self):
        if self.has_exception:
            return "Attempts: {0}, Error:\n{1}".format(self.attempt_number, "".join(traceback.format_tb(self.value[2])))
        else:
            return "Attempts: {0}, Value: {1}".format(self.attempt_number, self.value) 
Example 39
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: retrying.py    (MIT License) View Source Project 5 votes vote down vote up
def __repr__(self):
        if self.has_exception:
            return "Attempts: {0}, Error:\n{1}".format(self.attempt_number, "".join(traceback.format_tb(self.value[2])))
        else:
            return "Attempts: {0}, Value: {1}".format(self.attempt_number, self.value) 
Example 40
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: retrying.py    (MIT License) View Source Project 5 votes vote down vote up
def __repr__(self):
        if self.has_exception:
            return "Attempts: {0}, Error:\n{1}".format(self.attempt_number, "".join(traceback.format_tb(self.value[2])))
        else:
            return "Attempts: {0}, Value: {1}".format(self.attempt_number, self.value) 
Example 41
Project: jira_worklog_scanner   Author: pgarneau   File: retrying.py    (license) View Source Project 5 votes vote down vote up
def __repr__(self):
        if self.has_exception:
            return "Attempts: {0}, Error:\n{1}".format(self.attempt_number, "".join(traceback.format_tb(self.value[2])))
        else:
            return "Attempts: {0}, Value: {1}".format(self.attempt_number, self.value) 
Example 42
Project: b92statistike   Author: stalker314314   File: tools.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def exception_hook(exctype, value, tb):
    """
    Catch any unhandled exception and print its stack trace.
    Useful to see what is going on when scrapper crashes.
    """
    logger = logging.getLogger('main')
    logger.critical('{0}: {1}'.format(exctype, value))
    logger.critical(''.join(traceback.format_tb(tb))) 
Example 43
Project: zanph   Author: zanph   File: retrying.py    (license) View Source Project 5 votes vote down vote up
def __repr__(self):
        if self.has_exception:
            return "Attempts: {0}, Error:\n{1}".format(self.attempt_number, "".join(traceback.format_tb(self.value[2])))
        else:
            return "Attempts: {0}, Value: {1}".format(self.attempt_number, self.value) 
Example 44
Project: DL4MT   Author: thompsonb   File: score_server.py    (license) View Source Project 5 votes vote down vote up
def exception_handler(exception_type, exception, traceback):
    print("An unexpected {} exception occurred. Traceback will be written to "
          "debug log. The error message was: {}"
          .format(exception_type.__name__, exception))
    logging.debug("Traceback:")
    for item in format_tb(traceback):
        logging.debug(item.strip())
    sys.exit(2)
###end copied portion### 
Example 45
Project: hostapd-mana   Author: adde88   File: retrying.py    (license) View Source Project 5 votes vote down vote up
def __repr__(self):
        if self.has_exception:
            return "Attempts: {0}, Error:\n{1}".format(self.attempt_number, "".join(traceback.format_tb(self.value[2])))
        else:
            return "Attempts: {0}, Value: {1}".format(self.attempt_number, self.value) 
Example 46
Project: hostapd-mana   Author: adde88   File: config.py    (license) View Source Project 5 votes vote down vote up
def __str__(self):
        etype, evalue, etb = self.excinfo
        formatted = traceback.format_tb(etb)
        # The level of the tracebacks we want to print is hand crafted :(
        return repr(evalue) + '\n' + ''.join(formatted[2:]) 
Example 47
Project: hostapd-mana   Author: adde88   File: failure.py    (license) View Source Project 5 votes vote down vote up
def __init__(self, exc_class, exc_val, tb=None, address=None):
        log.debug("A failure! %s %s %s", exc_class, exc_val, format_tb(tb))
        self.exc_class = exc_class
        self.exc_val = exc_val
        self.tb = tb
        self._address = address
        unittest.TestCase.__init__(self) 
Example 48
Project: Sci-Finder   Author: snverse   File: retrying.py    (license) View Source Project 5 votes vote down vote up
def __repr__(self):
        if self.has_exception:
            return "Attempts: {0}, Error:\n{1}".format(self.attempt_number, "".join(traceback.format_tb(self.value[2])))
        else:
            return "Attempts: {0}, Value: {1}".format(self.attempt_number, self.value) 
Example 49
Project: Sci-Finder   Author: snverse   File: retrying.py    (license) View Source Project 5 votes vote down vote up
def __repr__(self):
        if self.has_exception:
            return "Attempts: {0}, Error:\n{1}".format(self.attempt_number, "".join(traceback.format_tb(self.value[2])))
        else:
            return "Attempts: {0}, Value: {1}".format(self.attempt_number, self.value) 
Example 50
Project: Qyoutube-dl   Author: lzambella   File: utils.py    (license) View Source Project 5 votes vote down vote up
def format_traceback(self):
        if self.traceback is None:
            return None
        return ''.join(traceback.format_tb(self.traceback))