Python traceback.format_tb() Examples

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

Example 1
Project: pyblish-win   Author: pyblish   File: test_traceback.py    GNU Lesser General Public License v3.0 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 2
Project: fastai_slack   Author: JovianML   File: __init__.py    MIT License 6 votes vote down vote up
def on_train_end(self, **ka):
        "Called at the end of training"
        # Check for exception
        ex = ka['exception']
        if ex:
            # Format exception
            ex_str = f'`{ex}`'
            # Extract and format stacktrace
            if hasattr(sys, 'last_traceback'):
                tb = traceback.format_tb(getattr(sys, 'last_traceback'))
                tb_str = '```\n' + '\n'.join(tb) + '\n```'
            else:
                tb_str = 'Failed to detect stacktrace'
            # Send exception and stacktrace
            self._send(['*Training failed with exception:', ex_str, tb_str])
        else:
            # Log success
            msg = ['*Training complete*']
            # Check if final metrics should be reported
            n_epochs = ka['n_epochs']
            if self.freq == 0 or n_epochs % self.freq > 0:
                # Send notification
                self._send_metrics(ka, msg)
            else:
                self._send(msg) 
Example 3
Project: core   Author: lifemapper   File: errorReporter.py    GNU General Public License v3.0 6 votes vote down vote up
def getErrorHash(err, tb):
   """
   @summary: This function gets a hash of an error that will be used as a file 
                name.  This goal of this function is to have the same errors 
                always hash to the same value.  So, avoid specific values in
                the error.  We'll try this with the error type and a trace back.
   @param err: An error object
   @param tb: (optional) The traceback for the error
   """
   h1 = hashlib.md5(str(err.__class__))
   if tb is not None:
      if isinstance(tb, basestring):
         h2 = hashlib.md5(tb)
      else:
         h2 = hashlib.md5(str(traceback.format_tb(tb)))
   else:
      h2 = hashlib.md5('')
   h3 = hashlib.md5(''.join((h1.hexdigest(), h2.hexdigest())))
   return h3.hexdigest() 
Example 4
Project: Splunk_CBER_App   Author: MHaggis   File: search_command.py    MIT License 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 5
Project: Trusted-Platform-Module-nova   Author: BU-NU-CLOUD-SP16   File: base.py    Apache License 2.0 6 votes vote down vote up
def serialize_args(fn):
    """Decorator that will do the arguments serialization before remoting."""
    def wrapper(obj, *args, **kwargs):
        args = [utils.strtime(arg) if isinstance(arg, datetime.datetime)
                else arg for arg in args]
        for k, v in six.iteritems(kwargs):
            if k == 'exc_val' and v:
                kwargs[k] = six.text_type(v)
            elif k == 'exc_tb' and v and not isinstance(v, six.string_types):
                kwargs[k] = ''.join(traceback.format_tb(v))
            elif isinstance(v, datetime.datetime):
                kwargs[k] = utils.strtime(v)
        if hasattr(fn, '__call__'):
            return fn(obj, *args, **kwargs)
        # NOTE(danms): We wrap a descriptor, so use that protocol
        return fn.__get__(None, obj)(*args, **kwargs)

    # NOTE(danms): Make this discoverable
    wrapper.remotable = getattr(fn, 'remotable', False)
    wrapper.original_fn = fn
    return (functools.wraps(fn)(wrapper) if hasattr(fn, '__call__')
            else classmethod(wrapper)) 
Example 6
Project: Trusted-Platform-Module-nova   Author: BU-NU-CLOUD-SP16   File: test_instance_action.py    Apache License 2.0 6 votes vote down vote up
def test_event_finish_with_failure_legacy_unicode(self, mock_finish):
        # Tests that traceback.format_tb is not called when exc_tb is unicode.
        self.useFixture(utils_fixture.TimeFixture(NOW))
        test_class = instance_action.InstanceActionEvent
        expected_packed_values = test_class.pack_action_event_finish(
            self.context, 'fake-uuid', 'fake-event', 'val',
            six.text_type('fake-tb'))
        expected_packed_values['finish_time'] = NOW

        mock_finish.return_value = fake_event
        event = test_class.event_finish_with_failure(
            self.context, 'fake-uuid', 'fake-event', exc_val='val',
            exc_tb=six.text_type('fake-tb'), want_result=True)
        mock_finish.assert_called_once_with(self.context,
                                            expected_packed_values)
        self.compare_obj(event, fake_event) 
Example 7
Project: Trusted-Platform-Module-nova   Author: BU-NU-CLOUD-SP16   File: test_instance_action.py    Apache License 2.0 6 votes vote down vote up
def test_event_finish_with_failure_no_result(self, mock_finish, mock_tb):
        # Tests that traceback.format_tb is not called when exc_tb is a str
        # and want_result is False, so no event should come back.
        mock_tb.return_value = 'fake-tb'
        self.useFixture(utils_fixture.TimeFixture(NOW))
        test_class = instance_action.InstanceActionEvent
        expected_packed_values = test_class.pack_action_event_finish(
            self.context, 'fake-uuid', 'fake-event', 'val', 'fake-tb')
        expected_packed_values['finish_time'] = NOW

        mock_finish.return_value = fake_event
        event = test_class.event_finish_with_failure(
            self.context, 'fake-uuid', 'fake-event', 'val', 'fake-tb',
            want_result=False)
        mock_finish.assert_called_once_with(self.context,
                                            expected_packed_values)
        self.assertIsNone(event)
        self.assertFalse(mock_tb.called) 
Example 8
Project: mpu   Author: MartinThoma   File: __init__.py    MIT License 6 votes vote down vote up
def exception_logging(exctype, value, tb):
    """
    Log exception by using the root logger.

    Use it as `sys.excepthook = exception_logging`.

    Parameters
    ----------
    exctype : type
    value : NameError
    tb : traceback
    """
    write_val = {
        "exception_type": str(exctype),
        "message": str(traceback.format_tb(tb, 10)),
    }
    logging.exception(str(write_val)) 
Example 9
Project: django-performance-testing   Author: PaesslerAG   File: core.py    BSD 3-Clause "New" or "Revised" License 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 10
Project: aiolocust   Author: kpidata   File: test_web.py    MIT License 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 11
Project: logger-py   Author: Sagacify   File: formatter.py    MIT License 6 votes vote down vote up
def error_serializer(error, error_traceback=None):
    """Serialize error as bunyan.

    When in doubt, ask what would bunyan do?
    https://github.com/trentm/node-bunyan/blob/master/lib/bunyan.js#L1141
    """
    if error_traceback is not None:
        trace = ''.join(traceback.format_tb(error_traceback, 15))
    elif error.__traceback__ is not None:
        trace = ''.join(traceback.format_tb(error.__traceback__, 15))
    else:
        # Exceptions that where never caught don't have a stack trace.
        trace = ''

    return {
        'message': ' '.join(str(arg) for arg in error.args),
        'name': error.__class__.__name__,
        'stack': trace
    } 
Example 12
Project: stoq   Author: PUNCH-Cyber   File: __init__.py    Apache License 2.0 6 votes vote down vote up
def format_exc(exc: Exception, limit: int = -1, msg: Optional[str] = None):
    """
    Format `Exceptions` for use with `Stoq` error handling
    
    """
    # Inspired from https://github.com/python/cpython/blob/3.7/Lib/traceback.py#L560-L563
    tb = traceback.format_tb(exc.__traceback__, limit=limit)[0].split('\n')[0].strip()
    stype = type(exc).__qualname__
    smod = type(exc).__module__
    if smod not in ('__main__', 'builtins'):
        stype = f'{smod}.{stype}'
    exc_str = f'{tb} ; {stype}: {str(exc)}'
    if msg:
        return f'{msg}: {exc_str}'
    else:
        return exc_str 
Example 13
Project: misp42splunk   Author: remg427   File: search_command.py    GNU Lesser General Public License v3.0 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 14
Project: misp42splunk   Author: remg427   File: search_command.py    GNU Lesser General Public License v3.0 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: misp42splunk   Author: remg427   File: search_command.py    GNU Lesser General Public License v3.0 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 16
Project: SplunkVersionControl   Author: gjanders   File: search_command.py    Apache License 2.0 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 17
Project: NiujiaoDebugger   Author: MrSrc   File: test_exceptions.py    GNU General Public License v3.0 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 18
Project: avantpy   Author: aroberge   File: exception_handling.py    MIT License 6 votes vote down vote up
def write_exception_info(exc, source):
    """Writes the information we have after processing the exception."""
    _ = gettext_lang.lang
    msg = handle_exception(exc, source)
    if msg is not None:
        write_err(msg)
    else:
        write_err(
            _("An exception was raised for which we have no simplified traceback:\n")
        )
        write_err("name: %s\n" % exc.__class__.__name__)
        write_err("args: " + str(exc.args) + "\n\n")
        write_err("Python traceback follows:\n\n")
        for item in traceback.format_tb(exc.__traceback__):
            write_err(item)
        write_err("\n") 
Example 19
Project: jbox   Author: jpush   File: base.py    MIT License 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 20
Project: nova   Author: ZhanHan   File: base.py    Apache License 2.0 6 votes vote down vote up
def serialize_args(fn):
    """Decorator that will do the arguments serialization before remoting."""
    def wrapper(obj, *args, **kwargs):
        args = [utils.strtime(arg) if isinstance(arg, datetime.datetime)
                else arg for arg in args]
        for k, v in six.iteritems(kwargs):
            if k == 'exc_val' and v:
                kwargs[k] = six.text_type(v)
            elif k == 'exc_tb' and v and not isinstance(v, six.string_types):
                kwargs[k] = ''.join(traceback.format_tb(v))
            elif isinstance(v, datetime.datetime):
                kwargs[k] = utils.strtime(v)
        if hasattr(fn, '__call__'):
            return fn(obj, *args, **kwargs)
        # NOTE(danms): We wrap a descriptor, so use that protocol
        return fn.__get__(None, obj)(*args, **kwargs)

    # NOTE(danms): Make this discoverable
    wrapper.remotable = getattr(fn, 'remotable', False)
    wrapper.original_fn = fn
    return (functools.wraps(fn)(wrapper) if hasattr(fn, '__call__')
            else classmethod(wrapper)) 
Example 21
Project: nova   Author: ZhanHan   File: test_instance_action.py    Apache License 2.0 6 votes vote down vote up
def test_event_finish_with_failure_legacy_unicode(self, mock_finish):
        # Tests that traceback.format_tb is not called when exc_tb is unicode.
        self.useFixture(utils_fixture.TimeFixture(NOW))
        test_class = instance_action.InstanceActionEvent
        expected_packed_values = test_class.pack_action_event_finish(
            self.context, 'fake-uuid', 'fake-event', 'val',
            six.text_type('fake-tb'))
        expected_packed_values['finish_time'] = NOW

        mock_finish.return_value = fake_event
        event = test_class.event_finish_with_failure(
            self.context, 'fake-uuid', 'fake-event', exc_val='val',
            exc_tb=six.text_type('fake-tb'), want_result=True)
        mock_finish.assert_called_once_with(self.context,
                                            expected_packed_values)
        self.compare_obj(event, fake_event) 
Example 22
Project: nova   Author: ZhanHan   File: test_instance_action.py    Apache License 2.0 6 votes vote down vote up
def test_event_finish_with_failure_no_result(self, mock_finish, mock_tb):
        # Tests that traceback.format_tb is not called when exc_tb is a str
        # and want_result is False, so no event should come back.
        mock_tb.return_value = 'fake-tb'
        self.useFixture(utils_fixture.TimeFixture(NOW))
        test_class = instance_action.InstanceActionEvent
        expected_packed_values = test_class.pack_action_event_finish(
            self.context, 'fake-uuid', 'fake-event', 'val', 'fake-tb')
        expected_packed_values['finish_time'] = NOW

        mock_finish.return_value = fake_event
        event = test_class.event_finish_with_failure(
            self.context, 'fake-uuid', 'fake-event', 'val', 'fake-tb',
            want_result=False)
        mock_finish.assert_called_once_with(self.context,
                                            expected_packed_values)
        self.assertIsNone(event)
        self.assertFalse(mock_tb.called) 
Example 23
Project: grand_central   Author: amiracle   File: search_command.py    MIT License 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 24
Project: SplunkForPCAP   Author: DanielSchwartz1   File: search_command.py    MIT License 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 25
Project: Spyce   Author: imec-myhdl   File: pyEdit.py    GNU Lesser General Public License v2.1 6 votes vote down vote up
def netlistMyhdlAct(self):
        ix = self.centralWidget.currentIndex()
        fname = self.centralWidget.widget(ix).fname
        dirname, basename = os.path.split(fname)
        dgmname, ext = os.path.splitext(basename)
        netlist_dir = os.path.join(os.curdir, 'netlist_myhdl', dgmname)
        
        #actual netlisting
#        netlist(fname, lang='myhdl', netlist_dir=netlist_dir)
        try:
            netlist(fname, lang='myhdl', netlist_dir=netlist_dir)
            # print message
            b = QtWidgets.QMessageBox()
            b.setWindowModality(QtCore.Qt.ApplicationModal)
            b.setText('netlist written in ' + netlist_dir)
            b.exec_()

        except Exception as e:
            exc_type, exc_value, exc_traceback = sys.exc_info()
            ee = traceback.format_tb(exc_traceback)
            error('netlisting of {} produced error:\n\nStacktrace:\n{}\nError message:\n{}'.format(fname, ''.join(ee), str(e))) 
Example 26
Project: TESTGIT   Author: B-ROY   File: queue.py    Apache License 2.0 6 votes vote down vote up
def start(self):
        if not self.task:
            raise "please set task"

        self.run = True
        while self.run:
            for task in self.task:
                try:
                    data = self.mq.block_pop()
                    if data != None:
                        data = json.loads(data[1])
                        task.__call__(data)
                except Exception, e:
                    print "exception", " * " * 10
                    print e
                    exc_type, exc_value, exc_traceback = sys.exc_info()
                    print traceback.format_tb(exc_traceback)
                    #time.sleep(self.time_sleep) 
Example 27
Project: pyblish-win   Author: pyblish   File: cgi.py    GNU Lesser General Public License v3.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 28
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: retrying.py    MIT License 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: Ansible-Example-AB2018   Author: umit-ozturk   File: package_facts.py    MIT License 5 votes vote down vote up
def main():
    global module
    module = AnsibleModule(argument_spec=dict(manager=dict()))
    manager = module.params['manager']
    packages = {}
    results = {}

    if manager is None or manager == 'auto':

        # detect!
        for manager_lib in ('rpm', 'apt'):
            try:
                dummy = __import__(manager_lib)
                manager = manager_lib
                break
            except ImportError:
                pass

        # FIXME: add more detection methods
    try:
        if manager == "rpm":
            packages = rpm_package_list()
        elif manager == "apt":
            packages = apt_package_list()
        else:
            if manager:
                results['msg'] = 'Unsupported package manager: %s' % manager
                results['skipped'] = True
            else:
                module.fail_json(msg='Could not detect supported package manager')
    except Exception as e:
        from traceback import format_tb
        module.fail_json(msg='Failed to retrieve packages: %s' % to_text(e), exception=format_tb(sys.exc_info()[2]))

    results['ansible_facts'] = {}
    # Set the facts, this will override the facts in ansible_facts that might
    # exist from previous runs when using operating system level or distribution
    # package managers
    results['ansible_facts']['packages'] = packages

    module.exit_json(**results) 
Example 30
Project: core   Author: lifemapper   File: lmobj.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, currargs=None, prevargs=None, lineno=None,  
                     doTrace=False, logger=None):
        """
        @todo: Exception will change in Python 3.0: update this.  
                 args will no longer exist, message can be any object
        @summary Constructor for the LMError class
        @param currargs: Current arguments (sequence or single string)
        @param prevargs: (optional) sequence of previous arguments for exception
                                being wrapped by LMError
        """
        super(LMError, self).__init__()
        self.lineno = lineno
        
        allargs = []
        if doTrace:
            sysinfo = sys.exc_info()
            tb = sysinfo[2]
            if tb is not None:
                tbargs = traceback.format_tb(tb)
            else:
                tbargs = [str(sysinfo)]
            
            for r in tbargs:
                allargs.append(r)
                
        if isinstance(currargs, TupleType) or isinstance(currargs, ListType):
            allargs.extend(currargs)
        elif currargs is not None:
            allargs.append(currargs)
            
        if isinstance(prevargs, TupleType) or isinstance(prevargs, ListType):
            allargs.extend(prevargs)
        elif prevargs is not None:
            allargs.append(prevargs)
        self.args = tuple(allargs)
        
# ............................................................................ 
Example 31
Project: core   Author: lifemapper   File: log.py    GNU General Public License v3.0 5 votes vote down vote up
def reportError(self, msg):
      if type(msg) is ListType or type(msg) is TupleType:
         msg = ' '.join(msg)
      sysinfo = sys.exc_info()
      argStr = '\n'.join(str(arg) for arg in sysinfo[1].args)
      tb = sysinfo[2]
      if tb is not None:
         tbStr = '\n'.join(traceback.format_tb(tb))
      else:
         tbStr = str(sysinfo)
      errStr = '\n'.join([tbStr, argStr])
      self.error(msg)
      self.error(errStr)

   # .............................................. 
Example 32
Project: Splunk_CBER_App   Author: MHaggis   File: external_search_command.py    MIT License 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: Trusted-Platform-Module-nova   Author: BU-NU-CLOUD-SP16   File: utils.py    Apache License 2.0 5 votes vote down vote up
def _get_fault_details(exc_info, error_code):
    details = ''
    if exc_info and error_code == 500:
        tb = exc_info[2]
        if tb:
            details = ''.join(traceback.format_tb(tb))
    return six.text_type(details) 
Example 34
Project: sic   Author: Yanixos   File: retrying.py    GNU General Public License v3.0 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 35
Project: AshsSDK   Author: thehappydinoa   File: retrying.py    MIT License 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: fitbit-googlefit   Author: praveendath92   File: auth_fitbit.py    GNU General Public License v3.0 5 votes vote down vote up
def _fmt_failure(self, message):
        tb = traceback.format_tb(sys.exc_info()[2])
        tb_html = '<pre>%s</pre>' % ('\n'.join(tb)) if tb else ''
        return self.failure_html % (message, tb_html) 
Example 37
Project: jawfish   Author: war-and-code   File: cgi.py    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 38
Project: jawfish   Author: war-and-code   File: cgi.py    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 39
Project: Repobot   Author: Desgard   File: retrying.py    MIT License 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: zun   Author: openstack   File: container_action.py    Apache License 2.0 5 votes vote down vote up
def event_finish(cls, context, container_uuid, event_name, exc_val=None,
                     exc_tb=None, want_result=None):
        if exc_val:
            exc_val = six.text_type(exc_val)
        if exc_tb and not isinstance(exc_tb, six.string_types):
            exc_tb = ''.join(traceback.format_tb(exc_tb))
        values = cls.pack_action_event_finish(context, container_uuid,
                                              event_name, exc_val=exc_val,
                                              exc_tb=exc_tb)
        db_event = dbapi.action_event_finish(context, values)
        if want_result:
            return cls._from_db_object(context, cls(context), db_event) 
Example 41
Project: aiolocust   Author: kpidata   File: test_web.py    MIT License 5 votes vote down vote up
def test_exceptions(self):
        try:
            raise Exception(u"A cool 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" % self.web_port)
        self.assertEqual(200, response.status_code)
        self.assertIn("A cool test exception", str(response.content))
        
        response = requests.get("http://127.0.0.1:%i/stats/requests" % self.web_port)
        self.assertEqual(200, response.status_code) 
Example 42
Project: aiolocust   Author: kpidata   File: runners.py    MIT License 5 votes vote down vote up
def __init__(self, locust_classes, options):
        super(LocalLocustRunner, self).__init__(locust_classes, options)

        # register listener thats logs the exception for the local runner
        def on_locust_error(locust_instance, exception, tb):
            formatted_tb = "".join(traceback.format_tb(tb))
            self.log_exception("local", str(exception), formatted_tb)
        events.locust_error += on_locust_error 
Example 43
Project: aiolocust   Author: kpidata   File: runners.py    MIT License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(SlaveLocustRunner, self).__init__(*args, **kwargs)
        self.client_id = socket.gethostname() + "_" + md5(str(time() + random.randint(0, 10000)).encode('utf-8')).hexdigest()
        
        self.client = rpc.Client(self.master_host, self.master_port)
        self.greenlet = Group()

        self.greenlet.spawn(self.worker).link_exception(callback=self.noop)
        self.client.send(Message("client_ready", None, self.client_id))
        self.greenlet.spawn(self.stats_reporter).link_exception(callback=self.noop)
        
        # register listener for when all locust users have hatched, and report it to the master node
        def on_hatch_complete(user_count):
            self.client.send(Message("hatch_complete", {"count":user_count}, self.client_id))
        events.hatch_complete += on_hatch_complete
        
        # register listener that adds the current number of spawned locusts to the report that is sent to the master node 
        def on_report_to_master(client_id, data):
            data["user_count"] = self.user_count
        events.report_to_master += on_report_to_master
        
        # register listener that sends quit message to master
        def on_quitting():
            self.client.send(Message("quit", None, self.client_id))
        events.quitting += on_quitting

        # register listener thats sends locust exceptions to master
        def on_locust_error(locust_instance, exception, tb):
            formatted_tb = "".join(traceback.format_tb(tb))
            self.client.send(Message("exception", {"msg" : str(exception), "traceback" : formatted_tb}, self.client_id))
        events.locust_error += on_locust_error 
Example 44
Project: fork   Author: srkunze   File: fork.py    MIT License 5 votes vote down vote up
def _safety_wrapper(callable_, *args, **kwargs):
    _pools_of.processes = None
    _pools_of.threads = None
    try:
        return callable_(*args, **kwargs)
    except BaseException as exc:
        raise TransportException(exc, traceback.format_tb(sys.exc_info()[2])[1:] + traceback.format_exception_only(type(exc), exc))
    finally:
        if _pools_of.processes:
            _pools_of.processes.shutdown()
        if _pools_of.threads:
            _pools_of.threads.shutdown() 
Example 45
Project: JukeBox   Author: gauravsarkar97   File: retrying.py    MIT License 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: misp42splunk   Author: remg427   File: external_search_command.py    GNU Lesser General Public License v3.0 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 47
Project: misp42splunk   Author: remg427   File: external_search_command.py    GNU Lesser General Public License v3.0 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: ' + six.text_type(error)
            self._logger.error(message + '\nTraceback:\n' + ''.join(traceback.format_tb(tb)))
            sys.exit(1) 
Example 48
Project: chattR   Author: patrickstocklin   File: retrying.py    GNU General Public License v2.0 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: DRCOG_Urbansim   Author: apdjustino   File: exception_formatter.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def formatExceptionInfo(custom_message = 'Unexpected error', maxTBlevel=5, plainText=False, log=True):
#    cla, exc, trbk = sys.exc_info()
    
#    excTb = traceback.format_tb(trbk, maxTBlevel)
#    excName = cla.__name__
#    try:
#        excArgs = exc.__dict__["args"]
#    except KeyError:
#        excArgs = "<no args>"
            
#    errorinfo = (excName, excArgs, excTb)

    format_message_and_error = lambda m, e: ('%s\n%s' % (m, e))  

    if log:
        logger.log_error(format_message_and_error(custom_message, traceback.format_exc()))

    fExc = format_message_and_error(custom_message, traceback.format_exc(limit=maxTBlevel))
    
    if plainText:
        return fExc
    else:
        fExc = fExc.replace('\t','   ').replace('\n','<br>').replace(' ', '&nbsp;')
        errorinfo = ('''<qt>%s</qt>
                     '''%(fExc))
        return errorinfo 
Example 50
Project: SplunkVersionControl   Author: gjanders   File: external_search_command.py    Apache License 2.0 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: ' + six.text_type(error)
            self._logger.error(message + '\nTraceback:\n' + ''.join(traceback.format_tb(tb)))
            sys.exit(1)