Python traceback.extract_tb() Examples

The following are code examples for showing how to use traceback.extract_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: code.py    GNU Lesser General Public License v3.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 2
Project: pyblish-win   Author: pyblish   File: test_zipimport.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def doTraceback(self, module):
        try:
            module.do_raise()
        except:
            tb = sys.exc_info()[2].tb_next

            f,lno,n,line = extract_tb(tb, 1)[0]
            self.assertEqual(line, raise_src.strip())

            f,lno,n,line = extract_stack(tb.tb_frame, 1)[0]
            self.assertEqual(line, raise_src.strip())

            s = StringIO.StringIO()
            print_tb(tb, 1, s)
            self.assertTrue(s.getvalue().endswith(raise_src))
        else:
            raise AssertionError("This ought to be impossible") 
Example 3
Project: pyblish-win   Author: pyblish   File: run.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def print_exception():
    import linecache
    linecache.checkcache()
    flush_stdout()
    efile = sys.stderr
    typ, val, tb = excinfo = sys.exc_info()
    sys.last_type, sys.last_value, sys.last_traceback = excinfo
    tbe = traceback.extract_tb(tb)
    print>>efile, '\nTraceback (most recent call last):'
    exclude = ("run.py", "rpc.py", "threading.py", "Queue.py",
               "RemoteDebugger.py", "bdb.py")
    cleanup_traceback(tbe, exclude)
    traceback.print_list(tbe, file=efile)
    lines = traceback.format_exception_only(typ, val)
    for line in lines:
        print>>efile, line, 
Example 4
Project: PyPadPlusPlus   Author: bitagoras   File: pyPadRemoteClient.py    GNU General Public License v3.0 6 votes vote down vote up
def showtraceback(self):
        """Display the exception that just occurred.
        The first two stack items are removed because it is
        not the user code."""
        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[:2]
            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(sys.stderr, list) 
Example 5
Project: PyPadPlusPlus   Author: bitagoras   File: pyPadClient.py    GNU General Public License v3.0 6 votes vote down vote up
def showtraceback(self):
        """Display the exception that just occurred."""
        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[:2]
            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(sys.stderr, list) 
Example 6
Project: Trusted-Platform-Module-nova   Author: BU-NU-CLOUD-SP16   File: test_virt_drivers.py    Apache License 2.0 6 votes vote down vote up
def catch_notimplementederror(f):
    """Decorator to simplify catching drivers raising NotImplementedError

    If a particular call makes a driver raise NotImplementedError, we
    log it so that we can extract this information afterwards as needed.
    """
    def wrapped_func(self, *args, **kwargs):
        try:
            return f(self, *args, **kwargs)
        except NotImplementedError:
            frame = traceback.extract_tb(sys.exc_info()[2])[-1]
            LOG.error("%(driver)s does not implement %(method)s "
                      "required for test %(test)s" %
                      {'driver': type(self.connection),
                       'method': frame[2], 'test': f.__name__})

    wrapped_func.__name__ = f.__name__
    wrapped_func.__doc__ = f.__doc__
    return wrapped_func 
Example 7
Project: deb-python-cassandra-driver   Author: openstack   File: __init__.py    Apache License 2.0 6 votes vote down vote up
def remove_cluster():
    if USE_CASS_EXTERNAL or KEEP_TEST_CLUSTER:
        return

    global CCM_CLUSTER
    if CCM_CLUSTER:
        log.debug("Removing cluster {0}".format(CCM_CLUSTER.name))
        tries = 0
        while tries < 100:
            try:
                CCM_CLUSTER.remove()
                CCM_CLUSTER = None
                return
            except OSError:
                ex_type, ex, tb = sys.exc_info()
                log.warn("{0}: {1} Backtrace: {2}".format(ex_type.__name__, ex, traceback.extract_tb(tb)))
                del tb
                tries += 1
                time.sleep(1)

        raise RuntimeError("Failed to remove cluster after 100 attempts") 
Example 8
Project: deb-python-cassandra-driver   Author: openstack   File: __init__.py    Apache License 2.0 6 votes vote down vote up
def execute_until_pass(session, query):
    tries = 0
    while tries < 100:
        try:
            return session.execute(query)
        except (ConfigurationException, AlreadyExists, InvalidRequest):
            log.warn("Received already exists from query {0}   not exiting".format(query))
            # keyspace/table was already created/dropped
            return
        except (OperationTimedOut, ReadTimeout, ReadFailure, WriteTimeout, WriteFailure):
            ex_type, ex, tb = sys.exc_info()
            log.warn("{0}: {1} Backtrace: {2}".format(ex_type.__name__, ex, traceback.extract_tb(tb)))
            del tb
            tries += 1

    raise RuntimeError("Failed to execute query after 100 attempts: {0}".format(query)) 
Example 9
Project: deb-python-cassandra-driver   Author: openstack   File: __init__.py    Apache License 2.0 6 votes vote down vote up
def execute_with_long_wait_retry(session, query, timeout=30):
    tries = 0
    while tries < 10:
        try:
            return session.execute(query, timeout=timeout)
        except (ConfigurationException, AlreadyExists):
            log.warn("Received already exists from query {0}    not exiting".format(query))
            # keyspace/table was already created/dropped
            return
        except (OperationTimedOut, ReadTimeout, ReadFailure, WriteTimeout, WriteFailure):
            ex_type, ex, tb = sys.exc_info()
            log.warn("{0}: {1} Backtrace: {2}".format(ex_type.__name__, ex, traceback.extract_tb(tb)))
            del tb
            tries += 1

    raise RuntimeError("Failed to execute query after 100 attempts: {0}".format(query)) 
Example 10
Project: deb-python-cassandra-driver   Author: openstack   File: test_consistency.py    Apache License 2.0 6 votes vote down vote up
def _query(self, session, keyspace, count, consistency_level=ConsistencyLevel.ONE):
        routing_key = struct.pack('>i', 0)
        for i in range(count):
            ss = SimpleStatement('SELECT * FROM cf WHERE k = 0',
                                 consistency_level=consistency_level,
                                 routing_key=routing_key)
            tries = 0
            while True:
                if tries > 100:
                    raise RuntimeError("Failed to execute query after 100 attempts: {0}".format(ss))
                try:
                    self.coordinator_stats.add_coordinator(session.execute_async(ss))
                    break
                except (OperationTimedOut, ReadTimeout):
                    ex_type, ex, tb = sys.exc_info()
                    log.warn("{0}: {1} Backtrace: {2}".format(ex_type.__name__, ex, traceback.extract_tb(tb)))
                    del tb
                    tries += 1
                    time.sleep(1) 
Example 11
Project: deb-python-cassandra-driver   Author: openstack   File: test_loadbalancingpolicies.py    Apache License 2.0 6 votes vote down vote up
def _insert(self, session, keyspace, count=12,
                consistency_level=ConsistencyLevel.ONE):
        session.execute('USE %s' % keyspace)
        ss = SimpleStatement('INSERT INTO cf(k, i) VALUES (0, 0)', consistency_level=consistency_level)

        tries = 0
        while tries < 100:
            try:
                execute_concurrent_with_args(session, ss, [None] * count)
                return
            except (OperationTimedOut, WriteTimeout, WriteFailure):
                ex_type, ex, tb = sys.exc_info()
                log.warn("{0}: {1} Backtrace: {2}".format(ex_type.__name__, ex, traceback.extract_tb(tb)))
                del tb
                tries += 1

        raise RuntimeError("Failed to execute query after 100 attempts: {0}".format(ss)) 
Example 12
Project: deb-python-cassandra-driver   Author: openstack   File: test_container_columns.py    Apache License 2.0 6 votes vote down vote up
def test_element_count_validation(self):
        """
        Tests that big collections are detected and raise an exception.
        """
        while True:
            try:
                TestSetModel.create(text_set=set(str(uuid4()) for i in range(65535)))
                break
            except WriteTimeout:
                ex_type, ex, tb = sys.exc_info()
                log.warning("{0}: {1} Backtrace: {2}".format(ex_type.__name__, ex, traceback.extract_tb(tb)))
                del tb
            except OperationTimedOut:
                #This will happen if the host is remote
                self.assertFalse(CASSANDRA_IP.startswith("127.0.0."))
        self.assertRaises(ValidationError, TestSetModel.create, **{'text_set': set(str(uuid4()) for i in range(65536))}) 
Example 13
Project: vscode-mayapy   Author: FXTD-ODYSSEY   File: pydevconsole_code_for_ironpython.py    MIT License 6 votes vote down vote up
def showtraceback(self, *args, **kwargs):
        """Display the exception that just occurred.

        We remove the first stack item because it is our own code.

        The output is written by self.write(), below.

        """
        try:
            type, value, tb = sys.exc_info()
            sys.last_type = type
            sys.last_value = value
            sys.last_traceback = tb
            tblist = traceback.extract_tb(tb)
            del tblist[:1]
            list = traceback.format_list(tblist)
            if list:
                list.insert(0, "Traceback (most recent call last):\n")
            list[len(list):] = traceback.format_exception_only(type, value)
        finally:
            tblist = tb = None
        map(self.write, list) 
Example 14
Project: vscode-mayapy   Author: FXTD-ODYSSEY   File: pydevconsole.py    MIT License 6 votes vote down vote up
def showtraceback(self, *args, **kwargs):
        """Display the exception that just occurred."""
        # Override for avoid using sys.excepthook PY-12600
        try:
            type, value, tb = sys.exc_info()
            sys.last_type = type
            sys.last_value = value
            sys.last_traceback = tb
            tblist = traceback.extract_tb(tb)
            del tblist[:1]
            lines = traceback.format_list(tblist)
            if lines:
                lines.insert(0, "Traceback (most recent call last):\n")
            lines.extend(traceback.format_exception_only(type, value))
        finally:
            tblist = tb = None
        sys.stderr.write(''.join(lines)) 
Example 15
Project: chattR   Author: patrickstocklin   File: autoreload.py    GNU General Public License v2.0 6 votes vote down vote up
def check_errors(fn):
    def wrapper(*args, **kwargs):
        try:
            fn(*args, **kwargs)
        except (ImportError, IndentationError, NameError, SyntaxError,
                TypeError, AttributeError):
            et, ev, tb = sys.exc_info()

            if getattr(ev, 'filename', None) is None:
                # get the filename from the last item in the stack
                filename = traceback.extract_tb(tb)[-1][0]
            else:
                filename = ev.filename

            if filename not in _error_files:
                _error_files.append(filename)

            raise

    return wrapper 
Example 16
Project: tornado-zh   Author: tao12345666333   File: concurrent_test.py    MIT License 6 votes vote down vote up
def test_future_traceback(self):
        @return_future
        @gen.engine
        def f(callback):
            yield gen.Task(self.io_loop.add_callback)
            try:
                1 / 0
            except ZeroDivisionError:
                self.expected_frame = traceback.extract_tb(
                    sys.exc_info()[2], limit=1)[0]
                raise
        try:
            yield f()
            self.fail("didn't get expected exception")
        except ZeroDivisionError:
            tb = traceback.extract_tb(sys.exc_info()[2])
            self.assertIn(self.expected_frame, tb)

# The following series of classes demonstrate and test various styles
# of use, with and without generators and futures. 
Example 17
Project: tornado-zh   Author: tao12345666333   File: concurrent_test.py    MIT License 6 votes vote down vote up
def test_future_traceback(self):
        @return_future
        @gen.engine
        def f(callback):
            yield gen.Task(self.io_loop.add_callback)
            try:
                1 / 0
            except ZeroDivisionError:
                self.expected_frame = traceback.extract_tb(
                    sys.exc_info()[2], limit=1)[0]
                raise
        try:
            yield f()
            self.fail("didn't get expected exception")
        except ZeroDivisionError:
            tb = traceback.extract_tb(sys.exc_info()[2])
            self.assertIn(self.expected_frame, tb)

# The following series of classes demonstrate and test various styles
# of use, with and without generators and futures. 
Example 18
Project: NiujiaoDebugger   Author: MrSrc   File: test_zipimport.py    GNU General Public License v3.0 6 votes vote down vote up
def doTraceback(self, module):
        try:
            module.do_raise()
        except:
            tb = sys.exc_info()[2].tb_next

            f,lno,n,line = extract_tb(tb, 1)[0]
            self.assertEqual(line, raise_src.strip())

            f,lno,n,line = extract_stack(tb.tb_frame, 1)[0]
            self.assertEqual(line, raise_src.strip())

            s = io.StringIO()
            print_tb(tb, 1, s)
            self.assertTrue(s.getvalue().endswith(raise_src))
        else:
            raise AssertionError("This ought to be impossible") 
Example 19
Project: NiujiaoDebugger   Author: MrSrc   File: test_pyexpat.py    GNU General Public License v3.0 6 votes vote down vote up
def test_exception(self):
        parser = expat.ParserCreate()
        parser.StartElementHandler = self.StartElementHandler
        try:
            parser.Parse(b"<a><b><c/></b></a>", 1)
            self.fail()
        except RuntimeError as e:
            self.assertEqual(e.args[0], 'a',
                             "Expected RuntimeError for element 'a', but" + \
                             " found %r" % e.args[0])
            # Check that the traceback contains the relevant line in pyexpat.c
            entries = traceback.extract_tb(e.__traceback__)
            self.assertEqual(len(entries), 3)
            self.check_traceback_entry(entries[0],
                                       "test_pyexpat.py", "test_exception")
            self.check_traceback_entry(entries[1],
                                       "pyexpat.c", "StartElement")
            self.check_traceback_entry(entries[2],
                                       "test_pyexpat.py", "StartElementHandler")
            if sysconfig.is_python_build():
                self.assertIn('call_with_frame("StartElement"', entries[1][3])


# Test Current* members: 
Example 20
Project: readysetstem-api   Author: readysetstem   File: testing_log.py    Apache License 2.0 6 votes vote down vote up
def write(self, test, test_type, exc):
        filename = line_num = func_name = line_text = exc_name = exc_msg = ''
        if exc:
            extracted_tb = traceback.extract_tb(exc.__traceback__)
            try:
                filename, line_num, func_name, line_text = list(extracted_tb[-1])
            except IndexError:
                pass
            exc_name = type(exc).__name__
            exc_msg = str(exc)

        test_func_name = str(test.__name__) if test else ""

        self.log.writerow([
            test_func_name,
            test_type,
            exc_name,
            filename,
            line_num,
            func_name,
            exc_msg
            ]) 
Example 21
Project: Nest   Author: ZhouYanzhao   File: cli.py    MIT License 6 votes vote down vote up
def hook_exceptions(self, logger: logging.RootLogger) -> None:
        """Format excetion traceback.
        
        Parameters:
            logger:
                The logger for logging exceptions.
        """

        def _hook(exc_type, value, exc_tb) -> None:
            nest_dir = os.path.dirname(os.path.abspath(__file__))
            traceback_str = ''
            idx = 0
            for file_name, line_number, func_name, text in traceback.extract_tb(exc_tb)[1:]:
                # skip Nest-related tracebacks to make it more readable
                if os.path.dirname(os.path.abspath(file_name)) == nest_dir:
                    continue
                idx += 1
                traceback_str += '\n  [%d] File "%s", line %d, in function "%s"\n    %s' % \
                    (idx, file_name, line_number, func_name, text)
            if traceback_str != '':
                traceback_str = 'Traceback: ' + traceback_str
            logger.critical('Exception occurred during resolving:\nType: %s\nMessage: %s\n%s' % \
                (exc_type.__name__, value, traceback_str))

        sys.excepthook = _hook 
Example 22
Project: nova   Author: ZhanHan   File: test_virt_drivers.py    Apache License 2.0 6 votes vote down vote up
def catch_notimplementederror(f):
    """Decorator to simplify catching drivers raising NotImplementedError

    If a particular call makes a driver raise NotImplementedError, we
    log it so that we can extract this information afterwards as needed.
    """
    def wrapped_func(self, *args, **kwargs):
        try:
            return f(self, *args, **kwargs)
        except NotImplementedError:
            frame = traceback.extract_tb(sys.exc_info()[2])[-1]
            LOG.error("%(driver)s does not implement %(method)s "
                      "required for test %(test)s" %
                      {'driver': type(self.connection),
                       'method': frame[2], 'test': f.__name__})

    wrapped_func.__name__ = f.__name__
    wrapped_func.__doc__ = f.__doc__
    return wrapped_func 
Example 23
Project: TESTGIT   Author: B-ROY   File: autoreload.py    Apache License 2.0 6 votes vote down vote up
def check_errors(fn):
    def wrapper(*args, **kwargs):
        try:
            fn(*args, **kwargs)
        except (ImportError, IndentationError, NameError, SyntaxError,
                TypeError, AttributeError):
            et, ev, tb = sys.exc_info()

            if getattr(ev, 'filename', None) is None:
                # get the filename from the last item in the stack
                filename = traceback.extract_tb(tb)[-1][0]
            else:
                filename = ev.filename

            if filename not in _error_files:
                _error_files.append(filename)

            raise

    return wrapper 
Example 24
Project: AneMo   Author: jspargo   File: autoreload.py    GNU General Public License v2.0 6 votes vote down vote up
def check_errors(fn):
    def wrapper(*args, **kwargs):
        try:
            fn(*args, **kwargs)
        except (ImportError, IndentationError, NameError, SyntaxError,
                TypeError, AttributeError):
            et, ev, tb = sys.exc_info()

            if getattr(ev, 'filename', None) is None:
                # get the filename from the last item in the stack
                filename = traceback.extract_tb(tb)[-1][0]
            else:
                filename = ev.filename

            if filename not in _error_files:
                _error_files.append(filename)

            raise

    return wrapper 
Example 25
Project: GTDWeb   Author: lanbing510   File: autoreload.py    GNU General Public License v2.0 6 votes vote down vote up
def check_errors(fn):
    def wrapper(*args, **kwargs):
        try:
            fn(*args, **kwargs)
        except (ImportError, IndentationError, NameError, SyntaxError,
                TypeError, AttributeError):
            et, ev, tb = sys.exc_info()

            if getattr(ev, 'filename', None) is None:
                # get the filename from the last item in the stack
                filename = traceback.extract_tb(tb)[-1][0]
            else:
                filename = ev.filename

            if filename not in _error_files:
                _error_files.append(filename)

            raise

    return wrapper 
Example 26
Project: liberator   Author: libscie   File: autoreload.py    Creative Commons Zero v1.0 Universal 6 votes vote down vote up
def check_errors(fn):
    def wrapper(*args, **kwargs):
        global _exception
        try:
            fn(*args, **kwargs)
        except Exception:
            _exception = sys.exc_info()

            et, ev, tb = _exception

            if getattr(ev, 'filename', None) is None:
                # get the filename from the last item in the stack
                filename = traceback.extract_tb(tb)[-1][0]
            else:
                filename = ev.filename

            if filename not in _error_files:
                _error_files.append(filename)

            raise

    return wrapper 
Example 27
Project: ironpython2   Author: IronLanguages   File: code.py    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 28
Project: ironpython2   Author: IronLanguages   File: test_zipimport.py    Apache License 2.0 6 votes vote down vote up
def doTraceback(self, module):
        try:
            module.do_raise()
        except:
            tb = sys.exc_info()[2].tb_next

            f,lno,n,line = extract_tb(tb, 1)[0]
            self.assertEqual(line, raise_src.strip())

            f,lno,n,line = extract_stack(tb.tb_frame, 1)[0]
            self.assertEqual(line, raise_src.strip())

            s = StringIO.StringIO()
            print_tb(tb, 1, s)
            self.assertTrue(s.getvalue().endswith(raise_src))
        else:
            raise AssertionError("This ought to be impossible") 
Example 29
Project: ServerMsgPush   Author: iakisey   File: utility.py    BSD 2-Clause "Simplified" License 6 votes vote down vote up
def output_wechat():
    from . import config
    exc_type, exc_value, exc_tb = sys.exc_info()
    exc_type_msg = exc_type.__name__ if exc_type else exc_type
    exc_tbs = sorted(
        [e for e in traceback.extract_tb(exc_tb)],
        key=lambda e: len(e.filename))
    exc_tb = exc_tbs[0] if exc_tbs else None
    exc_tb = exc_tb if exc_tb else None
    for user in eval(config['base']['maintainer']):
        send_msg(
            user,
            config['template']['url'],
            exc_type_msg,
            str(exc_value) if exc_value else None,
            *exc_tb
        ) if exc_type_msg or exc_value or exc_tb else None 
Example 30
Project: how-to-cython-mt2   Author: martysama0134   File: system.py    MIT License 6 votes vote down vote up
def GetExceptionString(excTitle):
	(excType, excMsg, excTraceBack)=sys.exc_info()
	excText=""
	excText+=_chr(10)

	import traceback
	traceLineList=traceback.extract_tb(excTraceBack)

	for traceLine in traceLineList:
		if traceLine[3]:
			excText+="%s(line:%d) %s - %s" % (traceLine[0], traceLine[1], traceLine[2], traceLine[3])
		else:
			excText+="%s(line:%d) %s"  % (traceLine[0], traceLine[1], traceLine[2])

		excText+=_chr(10)

	excText+=_chr(10)
	excText+="%s - %s:%s" % (excTitle, excType, excMsg)
	excText+=_chr(10)

	return excText 
Example 31
Project: banruo   Author: yingshang   File: concurrent_test.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_future_traceback(self):
        @return_future
        @gen.engine
        def f(callback):
            yield gen.Task(self.io_loop.add_callback)
            try:
                1 / 0
            except ZeroDivisionError:
                self.expected_frame = traceback.extract_tb(
                    sys.exc_info()[2], limit=1)[0]
                raise
        try:
            yield f()
            self.fail("didn't get expected exception")
        except ZeroDivisionError:
            tb = traceback.extract_tb(sys.exc_info()[2])
            self.assertIn(self.expected_frame, tb)

# The following series of classes demonstrate and test various styles
# of use, with and without generators and futures. 
Example 32
Project: banruo   Author: yingshang   File: autoreload.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def check_errors(fn):
    def wrapper(*args, **kwargs):
        global _exception
        try:
            fn(*args, **kwargs)
        except Exception:
            _exception = sys.exc_info()

            et, ev, tb = _exception

            if getattr(ev, 'filename', None) is None:
                # get the filename from the last item in the stack
                filename = traceback.extract_tb(tb)[-1][0]
            else:
                filename = ev.filename

            if filename not in _error_files:
                _error_files.append(filename)

            raise

    return wrapper 
Example 33
Project: AutoDL   Author: tanguofu   File: handlers.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _render_exception(self, exception):
        frames = extract_tb(exception.__traceback__)

        frame_html = []
        for frame in frames:
            frame_html.append(TRACEBACK_LINE_HTML.format(frame))

        return TRACEBACK_WRAPPER_INNER_HTML.format(
            exc_name=exception.__class__.__name__,
            exc_value=exception,
            frame_html=''.join(frame_html)) 
Example 34
Project: vulnerability-engine   Author: RedHatInsights   File: database_handler.py    GNU General Public License v2.0 5 votes vote down vote up
def __exit__(self, exception_type, exception_value, traceback):
        DatabasePoolHandler.return_connection(self.conn)
        if exception_type is InterfaceError or exception_type is DatabaseError:
            LOGGER.error("Exception type: %s. Exception value: %s. Traceback: %s", exception_type, exception_value,
                         str(extract_tb(traceback)))
            LOGGER.info("Trying to recover connection...")
            DatabasePoolHandler.create_connection_pool(DatabasePoolHandler.pool_size)
            LOGGER.info("Connection recovered")
            return True
        return False 
Example 35
Project: Paradrop   Author: ParadropLabs   File: output.py    Apache License 2.0 5 votes vote down vote up
def parseLogPrefix(tb):
    '''
    Takes a traceback returned by 'extract_tb' and returns the package, module,
    and line number
    '''
    path = tb.split('/')
    module = path[-1].replace('.py', '')
    package = path[-2]

    return module, package 
Example 36
Project: Paradrop   Author: ParadropLabs   File: output.py    Apache License 2.0 5 votes vote down vote up
def __call__(self, args):
        '''
        Catch twisted logs and make them fall inline with our logs.

        Only catch errors.

        Twisted will always pass a dict and guarantees [message, isError, and printed]
        will be in there.
        '''

        if args['isError'] == 0:
            return None

        # special handling of exception prefix logging
        try:
            tb = args['failure'].getTracebackObject()
            stacktrace = traceback.extract_tb(tb)[-1]

            module, package = parseLogPrefix(stacktrace[0])
            line = stacktrace[1]
        except Exception:
            package, module, line = "uknown", 'unknown', '??'

        ret = { \
            'message': str(args['failure'].getTraceback().strip()), \
            'type': self.type['name'], \
            'extra': {'details': 'floating print statement'}, \
            'package': package, \
            'module': module, \
            'timestamp': time.time(), \
            'pdid': 'UNSET', \
            'line': line \
        }

        return ret 
Example 37
Project: Paradrop   Author: ParadropLabs   File: output.py    Apache License 2.0 5 votes vote down vote up
def __call__(self, exception, random):
        '''
        The variable 'Random' is a leftover from the previous implementation and should be removed.
        '''

        # print exception.__traceback_
        ex_type, ex, tb = sys.exc_info()
        trace = traceback.extract_tb(tb)
        lastFrame = trace[-1]

        package, module = parseLogPrefix(lastFrame[0])
        line = lastFrame[1]

        message = type(exception).__name__ + ': ' + str(exception) + '\n'

        for x in trace:
            message += '  File "%s", line %d, in %s\n\t%s\n' % (x[0], x[1], x[2], x[3])

        ret = { \
            'message': message, \
            'type': self.type['name'], \
            'extra': {'details': 'floating print statement'}, \
            'package': package, \
            'module': module, \
            'timestamp': time.time(), \
            'pdid': 'UNSET', \
            'line': line \
        }

        return ret 
Example 38
Project: deb-python-cassandra-driver   Author: openstack   File: __init__.py    Apache License 2.0 5 votes vote down vote up
def drop_keyspace_shutdown_cluster(keyspace_name, session, cluster):
    try:
        execute_with_long_wait_retry(session, "DROP KEYSPACE {0}".format(keyspace_name))
    except:
        log.warn("Error encountered when droping keyspace {0}".format(keyspace_name))
        ex_type, ex, tb = sys.exc_info()
        log.warn("{0}: {1} Backtrace: {2}".format(ex_type.__name__, ex, traceback.extract_tb(tb)))
        del tb
    finally:
        log.warn("Shutting down cluster")
        cluster.shutdown() 
Example 39
Project: deb-python-cassandra-driver   Author: openstack   File: test_failure_types.py    Apache License 2.0 5 votes vote down vote up
def execute_helper(self, session, query):
        tries = 0
        while tries < 100:
            try:
                return session.execute(query)
            except OperationTimedOut:
                ex_type, ex, tb = sys.exc_info()
                log.warn("{0}: {1} Backtrace: {2}".format(ex_type.__name__, ex, traceback.extract_tb(tb)))
                del tb
                tries += 1

        raise RuntimeError("Failed to execute query after 100 attempts: {0}".format(query)) 
Example 40
Project: deb-python-cassandra-driver   Author: openstack   File: test_loadbalancingpolicies.py    Apache License 2.0 5 votes vote down vote up
def _query(self, session, keyspace, count=12,
               consistency_level=ConsistencyLevel.ONE, use_prepared=False):
        if use_prepared:
            query_string = 'SELECT * FROM %s.cf WHERE k = ?' % keyspace
            if not self.prepared or self.prepared.query_string != query_string:
                self.prepared = session.prepare(query_string)
                self.prepared.consistency_level = consistency_level
            for i in range(count):
                tries = 0
                while True:
                    if tries > 100:
                        raise RuntimeError("Failed to execute query after 100 attempts: {0}".format(self.prepared))
                    try:
                        self.coordinator_stats.add_coordinator(session.execute_async(self.prepared.bind((0,))))
                        break
                    except (OperationTimedOut, ReadTimeout, ReadFailure):
                        ex_type, ex, tb = sys.exc_info()
                        log.warn("{0}: {1} Backtrace: {2}".format(ex_type.__name__, ex, traceback.extract_tb(tb)))
                        del tb
                        tries += 1
        else:
            routing_key = struct.pack('>i', 0)
            for i in range(count):
                ss = SimpleStatement('SELECT * FROM %s.cf WHERE k = 0' % keyspace,
                                     consistency_level=consistency_level,
                                     routing_key=routing_key)
                tries = 0
                while True:
                    if tries > 100:
                        raise RuntimeError("Failed to execute query after 100 attempts: {0}".format(ss))
                    try:
                        self.coordinator_stats.add_coordinator(session.execute_async(ss))
                        break
                    except (OperationTimedOut, ReadTimeout, ReadFailure):
                        ex_type, ex, tb = sys.exc_info()
                        log.warn("{0}: {1} Backtrace: {2}".format(ex_type.__name__, ex, traceback.extract_tb(tb)))
                        del tb
                        tries += 1 
Example 41
Project: deb-python-cassandra-driver   Author: openstack   File: test_ssl.py    Apache License 2.0 5 votes vote down vote up
def validate_ssl_options(ssl_options):
        # find absolute path to client CA_CERTS
        tries = 0
        while True:
            if tries > 5:
                raise RuntimeError("Failed to connect to SSL cluster after 5 attempts")
            try:
                cluster = Cluster(protocol_version=PROTOCOL_VERSION, ssl_options=ssl_options)
                session = cluster.connect(wait_for_all_pools=True)
                break
            except Exception:
                ex_type, ex, tb = sys.exc_info()
                log.warn("{0}: {1} Backtrace: {2}".format(ex_type.__name__, ex, traceback.extract_tb(tb)))
                del tb
                tries += 1

        # attempt a few simple commands.
        insert_keyspace = """CREATE KEYSPACE ssltest
            WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '3'}
            """
        statement = SimpleStatement(insert_keyspace)
        statement.consistency_level = 3
        session.execute(statement)

        drop_keyspace = "DROP KEYSPACE ssltest"
        statement = SimpleStatement(drop_keyspace)
        statement.consistency_level = ConsistencyLevel.ANY
        session.execute(statement)

        cluster.shutdown() 
Example 42
Project: deb-python-cassandra-driver   Author: openstack   File: test_ssl.py    Apache License 2.0 5 votes vote down vote up
def test_can_connect_with_ssl_long_running(self):
        """
        Test to validate that long running ssl connections continue to function past thier timeout window

        @since 3.6.0
        @jira_ticket PYTHON-600
        @expected_result The client can connect via SSL and preform some basic operations over a period of longer then a minute

        @test_category connection:ssl
        """

        # find absolute path to client CA_CERTS
        abs_path_ca_cert_path = os.path.abspath(CLIENT_CA_CERTS)
        ssl_options = {'ca_certs': abs_path_ca_cert_path,
                       'ssl_version': ssl.PROTOCOL_TLSv1}
        tries = 0
        while True:
            if tries > 5:
                raise RuntimeError("Failed to connect to SSL cluster after 5 attempts")
            try:
                cluster = Cluster(protocol_version=PROTOCOL_VERSION, ssl_options=ssl_options)
                session = cluster.connect(wait_for_all_pools=True)
                break
            except Exception:
                ex_type, ex, tb = sys.exc_info()
                log.warn("{0}: {1} Backtrace: {2}".format(ex_type.__name__, ex, traceback.extract_tb(tb)))
                del tb
                tries += 1

        # attempt a few simple commands.

        for i in range(8):
            rs = session.execute("SELECT * FROM system.local")
            time.sleep(10)

        cluster.shutdown() 
Example 43
Project: deb-python-cassandra-driver   Author: openstack   File: test_concurrent.py    Apache License 2.0 5 votes vote down vote up
def execute_concurrent_helper(self, session, query, results_generator=False):
        count = 0
        while count < 100:
            try:
                return execute_concurrent(session, query, results_generator=False)
            except (ReadTimeout, WriteTimeout, OperationTimedOut, ReadFailure, WriteFailure):
                ex_type, ex, tb = sys.exc_info()
                log.warn("{0}: {1} Backtrace: {2}".format(ex_type.__name__, ex, traceback.extract_tb(tb)))
                del tb
                count += 1

        raise RuntimeError("Failed to execute query after 100 attempts: {0}".format(query)) 
Example 44
Project: deb-python-cassandra-driver   Author: openstack   File: test_concurrent.py    Apache License 2.0 5 votes vote down vote up
def execute_concurrent_args_helper(self, session, query, params, results_generator=False):
        count = 0
        while count < 100:
            try:
                return execute_concurrent_with_args(session, query, params, results_generator=results_generator)
            except (ReadTimeout, WriteTimeout, OperationTimedOut, ReadFailure, WriteFailure):
                ex_type, ex, tb = sys.exc_info()
                log.warn("{0}: {1} Backtrace: {2}".format(ex_type.__name__, ex, traceback.extract_tb(tb)))
                del tb

        raise RuntimeError("Failed to execute query after 100 attempts: {0}".format(query)) 
Example 45
Project: deb-python-cassandra-driver   Author: openstack   File: test_container_columns.py    Apache License 2.0 5 votes vote down vote up
def test_element_count_validation(self):
        """
        Tests that big collections are detected and raise an exception.
        """
        while True:
            try:
                TestListModel.create(text_list=[str(uuid4()) for i in range(65535)])
                break
            except WriteTimeout:
                ex_type, ex, tb = sys.exc_info()
                log.warn("{0}: {1} Backtrace: {2}".format(ex_type.__name__, ex, traceback.extract_tb(tb)))
                del tb
        self.assertRaises(ValidationError, TestListModel.create, **{'text_list': [str(uuid4()) for _ in range(65536)]}) 
Example 46
Project: sanic   Author: huge-success   File: handlers.py    MIT License 5 votes vote down vote up
def _render_exception(self, exception):
        frames = extract_tb(exception.__traceback__)

        frame_html = []
        for frame in frames:
            frame_html.append(TRACEBACK_LINE_HTML.format(frame))

        return TRACEBACK_WRAPPER_INNER_HTML.format(
            exc_name=exception.__class__.__name__,
            exc_value=exception,
            frame_html="".join(frame_html),
        ) 
Example 47
Project: quickfix.py   Author: tonyxty   File: cli.py    MIT License 5 votes vote down vote up
def run(filename, catch_interrupt=False):
    exceptions = (
        (Exception, KeyboardInterrupt) if catch_interrupt else Exception
    )
    try:
        run_path(filename, run_name="__main__")
    except exceptions:
        _, e, tb = sys.exc_info()
        return e, extract_tb(tb)[3:] 
Example 48
Project: wifi_taxonomy   Author: NetworkDeviceTaxonomy   File: wvtest.py    Apache License 2.0 5 votes vote down vote up
def _runtest(fname, f, innerfunc):
    import wvtest as _wvtestmod
    mod = inspect.getmodule(innerfunc)
    relpath = os.path.relpath(mod.__file__, os.getcwd()).replace('.pyc', '.py')
    print
    print 'Testing "%s" in %s:' % (fname, relpath)
    sys.stdout.flush()
    try:
        _run_in_chdir(os.path.split(mod.__file__)[0], f)
    except Exception, e:
        print
        print traceback.format_exc()
        tb = sys.exc_info()[2]
        _wvtestmod._result(repr(e), traceback.extract_tb(tb)[-1], 'EXCEPTION') 
Example 49
Project: Repobot   Author: Desgard   File: ultratb.py    MIT License 5 votes vote down vote up
def _fixed_getinnerframes(etb, context=1, tb_offset=0):
    LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5

    records = fix_frame_records_filenames(inspect.getinnerframes(etb, context))
    # If the error is at the console, don't build any context, since it would
    # otherwise produce 5 blank lines printed out (there is no file at the
    # console)
    rec_check = records[tb_offset:]
    try:
        rname = rec_check[0][1]
        if rname == '<ipython console>' or rname.endswith('<string>'):
            return rec_check
    except IndexError:
        pass

    aux = traceback.extract_tb(etb)
    assert len(records) == len(aux)
    for i, (file, lnum, _, _) in zip(range(len(records)), aux):
        maybeStart = lnum - 1 - context // 2
        start = max(maybeStart, 0)
        end = start + context
        lines = ulinecache.getlines(file)[start:end]
        buf = list(records[i])
        buf[LNUM_POS] = lnum
        buf[INDEX_POS] = lnum - 1 - start
        buf[LINES_POS] = lines
        records[i] = tuple(buf)
    return records[tb_offset:]

# Helper function -- largely belongs to VerboseTB, but we need the same
# functionality to produce a pseudo verbose TB for SyntaxErrors, so that they
# can be recognized properly by ipython.el's py-traceback-line-re
# (SyntaxErrors have to be treated specially because they have no traceback) 
Example 50
Project: Repobot   Author: Desgard   File: ultratb.py    MIT License 5 votes vote down vote up
def _format_list(self, extracted_list):
        """Format a list of traceback entry tuples for printing.

        Given a list of tuples as returned by extract_tb() or
        extract_stack(), return a list of strings ready for printing.
        Each string in the resulting list corresponds to the item with the
        same index in the argument list.  Each string ends in a newline;
        the strings may contain internal newlines as well, for those items
        whose source text line is not None.

        Lifted almost verbatim from traceback.py
        """

        Colors = self.Colors
        list = []
        for filename, lineno, name, line in extracted_list[:-1]:
            item = '  File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
                   (Colors.filename, py3compat.cast_unicode_py2(filename, "utf-8"), Colors.Normal,
                    Colors.lineno, lineno, Colors.Normal,
                    Colors.name, py3compat.cast_unicode_py2(name, "utf-8"), Colors.Normal)
            if line:
                item += '    %s\n' % line.strip()
            list.append(item)
        # Emphasize the last entry
        filename, lineno, name, line = extracted_list[-1]
        item = '%s  File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
               (Colors.normalEm,
                Colors.filenameEm, py3compat.cast_unicode_py2(filename, "utf-8"), Colors.normalEm,
                Colors.linenoEm, lineno, Colors.normalEm,
                Colors.nameEm, py3compat.cast_unicode_py2(name, "utf-8"), Colors.normalEm,
                Colors.Normal)
        if line:
            item += '%s    %s%s\n' % (Colors.line, line.strip(),
                                      Colors.Normal)
        list.append(item)
        return list