Python sys.exc_clear() Examples

The following are 30 code examples of sys.exc_clear(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module sys , or try the search function .
Example #1
Source File: OTBackTest.py    From OpenTrader with GNU Lesser General Public License v3.0 7 votes vote down vote up
def iMain():
    iRetval = 0
    oOm = None
    try:
        oOm = oOmain(sys.argv[1:])
    except KeyboardInterrupt:
        pass
    except Exception as e:
        sys.stderr.write("ERROR: " +str(e) +"\n" + \
                         traceback.format_exc(10) +"\n")
        sys.stderr.flush()
        sys.exc_clear()
        iRetval = 1
    finally:
        if oOm: oOm.vClose()
    return iRetval 
Example #2
Source File: backdoor.py    From satori with Apache License 2.0 7 votes vote down vote up
def handle(self, conn, address):
        """
        Interact with one remote user.

        .. versionchanged:: 1.1b2 Each connection gets its own
            ``locals`` dictionary. Previously they were shared in a
            potentially unsafe manner.
        """
        fobj = conn.makefile(mode="rw")
        fobj = _fileobject(conn, fobj, self.stderr)
        getcurrent()._fileobj = fobj

        getcurrent().switch_in()
        try:
            console = InteractiveConsole(self._create_interactive_locals())
            console.interact(banner=self.banner)
        except SystemExit:  # raised by quit()
            if hasattr(sys, 'exc_clear'): # py2
                sys.exc_clear()
        finally:
            conn.close()
            fobj.close() 
Example #3
Source File: _ssl2.py    From satori with Apache License 2.0 6 votes vote down vote up
def do_handshake(self):
        """Perform a TLS/SSL handshake."""
        while True:
            try:
                return self._sslobj.do_handshake()
            except SSLError as ex:
                if ex.args[0] == SSL_ERROR_WANT_READ:
                    if self.timeout == 0.0:
                        raise
                    sys.exc_clear()
                    self._wait(self._read_event, timeout_exc=_SSLErrorHandshakeTimeout)
                elif ex.args[0] == SSL_ERROR_WANT_WRITE:
                    if self.timeout == 0.0:
                        raise
                    sys.exc_clear()
                    self._wait(self._write_event, timeout_exc=_SSLErrorHandshakeTimeout)
                else:
                    raise 
Example #4
Source File: lambda_function.py    From aws-elemental-instant-video-highlights with Apache License 2.0 6 votes vote down vote up
def put_dynamo_main(dynamo_object):
    print("put_dynamo to table: " + str(DYNAMO_MAIN))
    table = dynamodb.Table(DYNAMO_MAIN)
    try:
        response = table.put_item(
            Item=dynamo_object,
            ConditionExpression='attribute_not_exists(id_filename)'
        )
        # print("dynamo put_item succeeded: {}".format(response))
    except Exception as e:
        # Ignore the ConditionalCheckFailedException, bubble up other exceptions.
        print("ERROR: dynamo BORKED: {}".format(e)) 
        print('broken dynamo: {}'.format(dynamo_object))
        if e.response['Error']['Code'] != 'ConditionalCheckFailedException':
            raise e
        sys.exc_clear() 
Example #5
Source File: lambda_function.py    From aws-elemental-instant-video-highlights with Apache License 2.0 6 votes vote down vote up
def put_dynamo_main(dynamo_object):
    print("put_dynamo to table: " + str(DYNAMO_MAIN))
    table = dynamodb.Table(DYNAMO_MAIN)
    try:
        response = table.put_item(
            Item=dynamo_object,
            ConditionExpression='attribute_not_exists(id_filename)'
        )
        print("dynamo put_item succeeded: {}".format(response))
    except Exception as e:
        # Ignore the ConditionalCheckFailedException, bubble up other exceptions.
        print("pizzaninja: {}".format(e)) 
        print('broken dynamo: {}'.format(dynamo_object))
        if e.response['Error']['Code'] != 'ConditionalCheckFailedException':
            raise e
        sys.exc_clear() 
Example #6
Source File: lambda_function.py    From aws-elemental-instant-video-highlights with Apache License 2.0 6 votes vote down vote up
def put_dynamo_main(dynamo_object):
    print("put_dynamo to table: " + str(DYNAMO_MAIN))
    print("dynamo_object: {}".format(dynamo_object))    
    table = dynamodb.Table(DYNAMO_MAIN)
    try:
        response = table.put_item(
            Item=dynamo_object,
            ConditionExpression='attribute_not_exists(id_filename)'
        )
        print("dynamo put_item succeeded: {}".format(response))
    except Exception as e:
        # Ignore the ConditionalCheckFailedException, bubble up other exceptions.
        print("pizzaninja: {}".format(e)) 
        print('broken dynamo: {}'.format(dynamo_object))
        if e.response['Error']['Code'] != 'ConditionalCheckFailedException':
            raise e
        sys.exc_clear() 
Example #7
Source File: lambda_function.py    From aws-elemental-instant-video-highlights with Apache License 2.0 6 votes vote down vote up
def put_dynamo_main(dynamo_object):
    print("put_dynamo to table: " + str(DYNAMO_MAIN))
    table = dynamodb.Table(DYNAMO_MAIN)
    try:
        response = table.put_item(
            Item=dynamo_object,
            ConditionExpression='attribute_not_exists(id_filename)'
        )
        print("dynamo put_item succeeded: {}".format(response))
    except Exception as e:
        # Ignore the ConditionalCheckFailedException, bubble up other exceptions.
        print("pizzaninja: {}".format(e)) 
        print('broken dynamo: {}'.format(dynamo_object))
        if e.response['Error']['Code'] != 'ConditionalCheckFailedException':
            raise e
        sys.exc_clear() 
Example #8
Source File: lambda_function.py    From aws-elemental-instant-video-highlights with Apache License 2.0 6 votes vote down vote up
def put_dynamo_main(dynamo_object):
    print("put_dynamo to table: " + str(DYNAMO_MAIN))
    table = dynamodb.Table(DYNAMO_MAIN)
    try:
        response = table.put_item(
            Item=dynamo_object,
            ConditionExpression='attribute_not_exists(id_filename)'
        )
        print("dynamo put_item succeeded: {}".format(response))
    except Exception as e:
        # Ignore the ConditionalCheckFailedException, bubble up other exceptions.
        print("pizzaninja: {}".format(e)) 
        print('broken dynamo: {}'.format(dynamo_object))
        if e.response['Error']['Code'] != 'ConditionalCheckFailedException':
            raise e
        sys.exc_clear() 
Example #9
Source File: test_json.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_failureStructurePreserved(self):
        """
        Round-tripping a failure through L{eventAsJSON} preserves its class and
        structure.
        """
        events = []
        log = Logger(observer=events.append)
        try:
            1 / 0
        except ZeroDivisionError:
            f = Failure()
            log.failure("a message about failure", f)
        import sys
        if sys.exc_info()[0] is not None:
            # Make sure we don't get the same Failure by accident.
            sys.exc_clear()
        self.assertEqual(len(events), 1)
        loaded = eventFromJSON(self.savedEventJSON(events[0]))['log_failure']
        self.assertIsInstance(loaded, Failure)
        self.assertTrue(loaded.check(ZeroDivisionError))
        self.assertIsInstance(loaded.getTraceback(), str) 
Example #10
Source File: PikaChart.py    From OTMql4AMQP with GNU Lesser General Public License v3.0 6 votes vote down vote up
def vPikaCallbackOnListener(self, oChannel, oMethod, oProperties, sBody):
        assert sBody, "vPikaCallbackOnListener: no sBody received"
        oChannel.basic_ack(delivery_tag=oMethod.delivery_tag)
        sMess = "vPikaCallbackOnListener Listened: %r" % sBody
        sys.stdout.write("INFO: " +sMess +"\n")
        sys.stdout.flush()
        # we will assume that the sBody
        # is a "|" seperated list of command and arguments
        # FixMe: the sMess must be in the right format
        # FixMe: refactor for multiple charts:
        # we must push to the right chart
        try:
            self.vPikaDispatchOnListener(sBody, oProperties)
        except Exception as e:
            sys.stdout.write("ERROR: " +str(e) +"\n" + \
                             traceback.format_exc(10) +"\n")
            sys.stdout.flush()
            sys.exc_clear()

    # unused 
Example #11
Source File: __init__.py    From OTMql4AMQP with GNU Lesser General Public License v3.0 6 votes vote down vote up
def vPyDeInit():
    global oTKINTER_ROOT, sSTDOUT_FD
    if sSTDOUT_FD:
        try:
            sys.stdout = sys.__stdout__
            sys.stderr = sys.__stderr__
            sName = sSTDOUT_FD.name
            # sShowInfo('vPyDeInit', "Closing %s" % (sName,))
            sSTDOUT_FD.write('INFO : vPyDeInit ' + "Closing outfile %s\n" % (sName,))
            # oLOG.shutdown()
            sSTDOUT_FD.flush()
            sSTDOUT_FD.close()
            sSTDOUT_FD = None
        except Exception as e:
            # You probably have not stdout so no point in logging it!
            print "Error closing %s\n%s" % (sSTDOUT_FD, str(e),)
            sys.exc_clear()

    if oTKINTER_ROOT:
        oTKINTER_ROOT.destroy()
        oTKINTER_ROOT = None

    sys.exc_clear() 
Example #12
Source File: test_exceptions.py    From mako with MIT License 6 votes vote down vote up
def test_tback_no_trace_from_py_file(self):
        try:
            t = self._file_template("runtimeerr.html")
            t.render()
        except:
            t, v, tback = sys.exc_info()

        if not compat.py3k:
            # blow away tracebaack info
            sys.exc_clear()

        # and don't even send what we have.
        html_error = exceptions.html_error_template().render_unicode(
            error=v, traceback=None
        )
        assert (
            "local variable 'y' referenced before assignment"
            in html_error
        ) 
Example #13
Source File: test_excinfo.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_clear_nested_func(self):
        def f():
            try:
                self.A(13)
                raise ValueError(54)
            except:
                self.A(54)
                sys.exc_clear()
                self.A(None)
            self.A(None)  # will be restored after func returns
        #
        try:
            raise ValueError(13)
        except:
            self.A(13)
            f()  # calls sys.exc_clear()
            self.A(13)  # still restored even after clear
        self.A(13)


    # Test clearing when there isn't an active exception (outside except block) 
Example #14
Source File: test_excinfo.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_clear_no_active_ex(self):
        self.A(None)
        sys.exc_clear()
        self.A(None)
        try:
            sys.exc_clear()
            self.A(None)
        except:
            pass
        try:
            pass
        finally:
            sys.exc_clear()
            self.A(None)
        self.A(None)

    #========================================================
    # With's Pep (http://www.python.org/dev/peps/pep-0343/) says the
    # __exit__ can be invoked by an except block,
    # but unlike a normal except, that shouldn't set sys.exc_info(). 
Example #15
Source File: _ssl2.py    From satori with Apache License 2.0 6 votes vote down vote up
def _sslobj_shutdown(self):
        while True:
            try:
                return self._sslobj.shutdown()
            except SSLError as ex:
                if ex.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
                    return ''
                elif ex.args[0] == SSL_ERROR_WANT_READ:
                    if self.timeout == 0.0:
                        raise
                    sys.exc_clear()
                    self._wait(self._read_event, timeout_exc=_SSLErrorReadTimeout)
                elif ex.args[0] == SSL_ERROR_WANT_WRITE:
                    if self.timeout == 0.0:
                        raise
                    sys.exc_clear()
                    self._wait(self._write_event, timeout_exc=_SSLErrorWriteTimeout)
                else:
                    raise 
Example #16
Source File: default.py    From repository.guilouz with GNU General Public License v2.0 6 votes vote down vote up
def _edit_db_string( self,preset,type,label ):
        keyboard = xbmc.Keyboard(preset)
        keyboard.doModal()
        if (keyboard.isConfirmed()):
            try:
                InputLabel=keyboard.getText()
                conv=time.strptime(InputLabel,"%d/%m/%Y")
              #  InputLabel = Time.strftime('%Y-%m-%d')
                InputLabel = time.strftime("%Y-%m-%d",conv)
            except Exception:
                sys.exc_clear()
            if ((type == "Song") or (type == "Album") or (type == "Artist")):
                xbmc.executeJSONRPC('{"jsonrpc": "2.0", "id": 1, "method": "AudioLibrary.Set%sDetails", "params": { "%s": "%s", "%sid":%s }}' % (type,label,InputLabel,type.lower(),self.DBID))
            else:
                xbmc.executeJSONRPC('{"jsonrpc": "2.0", "id": 1, "method": "VideoLibrary.Set%sDetails", "params": { "%s": "%s", "%sid":%s }}' % (type,label,InputLabel,type.lower(),self.DBID))
        else:
            return "" 
Example #17
Source File: _ssl2.py    From satori with Apache License 2.0 6 votes vote down vote up
def write(self, data):
        """Write DATA to the underlying SSL channel.  Returns
        number of bytes of DATA actually transmitted."""
        while True:
            try:
                return self._sslobj.write(data)
            except SSLError as ex:
                if ex.args[0] == SSL_ERROR_WANT_READ:
                    if self.timeout == 0.0:
                        raise
                    sys.exc_clear()
                    self._wait(self._read_event, timeout_exc=_SSLErrorWriteTimeout)
                elif ex.args[0] == SSL_ERROR_WANT_WRITE:
                    if self.timeout == 0.0:
                        raise
                    sys.exc_clear()
                    self._wait(self._write_event, timeout_exc=_SSLErrorWriteTimeout)
                else:
                    raise 
Example #18
Source File: os.py    From satori with Apache License 2.0 6 votes vote down vote up
def nb_write(fd, buf):
        """Write bytes from buffer `buf` to file descriptor `fd`. Return the
        number of bytes written.

        The file descriptor must be in non-blocking mode.
        """
        hub, event = None, None
        while True:
            try:
                return _write(fd, buf)
            except OSError as e:
                if e.errno not in ignored_errors:
                    raise
                if not PY3:
                    sys.exc_clear()
            if hub is None:
                hub = get_hub()
                event = hub.loop.io(fd, 2)
            hub.wait(event) 
Example #19
Source File: os.py    From satori with Apache License 2.0 6 votes vote down vote up
def nb_read(fd, n):
        """Read up to `n` bytes from file descriptor `fd`. Return a string
        containing the bytes read. If end-of-file is reached, an empty string
        is returned.

        The descriptor must be in non-blocking mode.
        """
        hub, event = None, None
        while True:
            try:
                return _read(fd, n)
            except OSError as e:
                if e.errno not in ignored_errors:
                    raise
                if not PY3:
                    sys.exc_clear()
            if hub is None:
                hub = get_hub()
                event = hub.loop.io(fd, 1)
            hub.wait(event) 
Example #20
Source File: test_json.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_failureStructurePreserved(self):
        """
        Round-tripping a failure through L{eventAsJSON} preserves its class and
        structure.
        """
        events = []
        log = Logger(observer=events.append)
        try:
            1 / 0
        except ZeroDivisionError:
            f = Failure()
            log.failure("a message about failure", f)
        import sys
        if sys.exc_info()[0] is not None:
            # Make sure we don't get the same Failure by accident.
            sys.exc_clear()
        self.assertEqual(len(events), 1)
        loaded = eventFromJSON(self.savedEventJSON(events[0]))['log_failure']
        self.assertIsInstance(loaded, Failure)
        self.assertTrue(loaded.check(ZeroDivisionError))
        self.assertIsInstance(loaded.getTraceback(), str) 
Example #21
Source File: ctx.py    From Building-Recommendation-Systems-with-Python with MIT License 5 votes vote down vote up
def push(self):
        """Binds the request context to the current context."""
        # If an exception occurs in debug mode or if context preservation is
        # activated under exception situations exactly one context stays
        # on the stack.  The rationale is that you want to access that
        # information under debug situations.  However if someone forgets to
        # pop that context again we want to make sure that on the next push
        # it's invalidated, otherwise we run at risk that something leaks
        # memory.  This is usually only a problem in test suite since this
        # functionality is not active in production environments.
        top = _request_ctx_stack.top
        if top is not None and top.preserved:
            top.pop(top._preserved_exc)

        # Before we push the request context we have to ensure that there
        # is an application context.
        app_ctx = _app_ctx_stack.top
        if app_ctx is None or app_ctx.app != self.app:
            app_ctx = self.app.app_context()
            app_ctx.push()
            self._implicit_app_ctx_stack.append(app_ctx)
        else:
            self._implicit_app_ctx_stack.append(None)

        if hasattr(sys, 'exc_clear'):
            sys.exc_clear()

        _request_ctx_stack.push(self)

        # Open the session at the moment that the request context is available.
        # This allows a custom open_session method to use the request context.
        # Only open a new session if this is the first time the request was
        # pushed, otherwise stream_with_context loses the session.
        if self.session is None:
            session_interface = self.app.session_interface
            self.session = session_interface.open_session(
                self.app, self.request
            )

            if self.session is None:
                self.session = session_interface.make_null_session(self.app) 
Example #22
Source File: _compat.py    From Building-Recommendation-Systems-with-Python with MIT License 5 votes vote down vote up
def __exit__(self, *args):
            if hasattr(sys, 'exc_clear'):
                # Python 3 (PyPy3) doesn't have exc_clear
                sys.exc_clear() 
Example #23
Source File: ctx.py    From Building-Recommendation-Systems-with-Python with MIT License 5 votes vote down vote up
def push(self):
        """Binds the request context to the current context."""
        # If an exception occurs in debug mode or if context preservation is
        # activated under exception situations exactly one context stays
        # on the stack.  The rationale is that you want to access that
        # information under debug situations.  However if someone forgets to
        # pop that context again we want to make sure that on the next push
        # it's invalidated, otherwise we run at risk that something leaks
        # memory.  This is usually only a problem in test suite since this
        # functionality is not active in production environments.
        top = _request_ctx_stack.top
        if top is not None and top.preserved:
            top.pop(top._preserved_exc)

        # Before we push the request context we have to ensure that there
        # is an application context.
        app_ctx = _app_ctx_stack.top
        if app_ctx is None or app_ctx.app != self.app:
            app_ctx = self.app.app_context()
            app_ctx.push()
            self._implicit_app_ctx_stack.append(app_ctx)
        else:
            self._implicit_app_ctx_stack.append(None)

        if hasattr(sys, 'exc_clear'):
            sys.exc_clear()

        _request_ctx_stack.push(self)

        # Open the session at the moment that the request context is available.
        # This allows a custom open_session method to use the request context.
        # Only open a new session if this is the first time the request was
        # pushed, otherwise stream_with_context loses the session.
        if self.session is None:
            session_interface = self.app.session_interface
            self.session = session_interface.open_session(
                self.app, self.request
            )

            if self.session is None:
                self.session = session_interface.make_null_session(self.app) 
Example #24
Source File: fileobject.py    From satori with Apache License 2.0 5 votes vote down vote up
def _exc_clear():
        sys.exc_clear() 
Example #25
Source File: ctx.py    From scylla with Apache License 2.0 5 votes vote down vote up
def push(self):
        """Binds the app context to the current context."""
        self._refcnt += 1
        if hasattr(sys, 'exc_clear'):
            sys.exc_clear()
        _app_ctx_stack.push(self)
        appcontext_pushed.send(self.app) 
Example #26
Source File: test_failure.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def test_findNoFailure(self):
        """
        Outside of an exception handler, _findFailure should return None.
        """
        if sys.version_info < (3, 0):
            sys.exc_clear()
        self.assertIsNone(sys.exc_info()[-1]) #environment sanity check
        self.assertIsNone(failure.Failure._findFailure()) 
Example #27
Source File: ctx.py    From scylla with Apache License 2.0 5 votes vote down vote up
def push(self):
        """Binds the request context to the current context."""
        # If an exception occurs in debug mode or if context preservation is
        # activated under exception situations exactly one context stays
        # on the stack.  The rationale is that you want to access that
        # information under debug situations.  However if someone forgets to
        # pop that context again we want to make sure that on the next push
        # it's invalidated, otherwise we run at risk that something leaks
        # memory.  This is usually only a problem in test suite since this
        # functionality is not active in production environments.
        top = _request_ctx_stack.top
        if top is not None and top.preserved:
            top.pop(top._preserved_exc)

        # Before we push the request context we have to ensure that there
        # is an application context.
        app_ctx = _app_ctx_stack.top
        if app_ctx is None or app_ctx.app != self.app:
            app_ctx = self.app.app_context()
            app_ctx.push()
            self._implicit_app_ctx_stack.append(app_ctx)
        else:
            self._implicit_app_ctx_stack.append(None)

        if hasattr(sys, 'exc_clear'):
            sys.exc_clear()

        _request_ctx_stack.push(self)

        # Open the session at the moment that the request context is available.
        # This allows a custom open_session method to use the request context.
        # Only open a new session if this is the first time the request was
        # pushed, otherwise stream_with_context loses the session.
        if self.session is None:
            session_interface = self.app.session_interface
            self.session = session_interface.open_session(
                self.app, self.request
            )

            if self.session is None:
                self.session = session_interface.make_null_session(self.app) 
Example #28
Source File: test_failure.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def test_ConstructionFails(self):
        """
        Creating a Failure with no arguments causes it to try to discover the
        current interpreter exception state.  If no such state exists, creating
        the Failure should raise a synchronous exception.
        """
        if sys.version_info < (3, 0):
            sys.exc_clear()
        self.assertRaises(failure.NoCurrentExceptionError, failure.Failure) 
Example #29
Source File: _compat.py    From Building-Recommendation-Systems-with-Python with MIT License 5 votes vote down vote up
def __exit__(self, *args):
            if hasattr(sys, 'exc_clear'):
                # Python 3 (PyPy3) doesn't have exc_clear
                sys.exc_clear() 
Example #30
Source File: test_sys.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_exc_clear(self):
        self.assertRaises(TypeError, sys.exc_clear, 42)

        # Verify that exc_info is present and matches exc, then clear it, and
        # check that it worked.
        def clear_check(exc):
            typ, value, traceback = sys.exc_info()
            self.assertTrue(typ is not None)
            self.assertTrue(value is exc)
            self.assertTrue(traceback is not None)

            with test.test_support.check_py3k_warnings():
                sys.exc_clear()

            typ, value, traceback = sys.exc_info()
            self.assertTrue(typ is None)
            self.assertTrue(value is None)
            self.assertTrue(traceback is None)

        def clear():
            try:
                raise ValueError, 42
            except ValueError, exc:
                clear_check(exc)

        # Raise an exception and check that it can be cleared