sys.exc_clear

Here are the examples of the python api sys.exc_clear taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

169 Examples 7

Example 1

Project: AvsPmod
Source File: avisynth.py
View license
    def get_frame(self,n):
        self._error = None
        try:
            return AVS_VideoFrame(avs_get_frame(self, n))
        except Exception as err:
            # Clear the exception traceback in order to avoid keeping an 
            # additional reference to the clip, which would cause its 
            # destruction to be postponed until the process finishes (if 
            # that's the last exception). It would then cause a new exception 
            # as the env doesn't exist anymore at that point (maybe even 
            # avisynth was already unloaded).
            self._error = ''.join(traceback.format_exception_only(type(err), err))
            sys.exc_clear()

Example 2

Project: regulations-scraper
Source File: gevent_mongo.py
View license
    def __new__(cls,db_name,size=5,*args,**kwargs):
        if not hasattr(cls,'_instance'):
	    # use your own config library
            cls._instance = object.__new__(cls)
            cls._instance.queue = Queue(size)
            for x in xrange(size):
                try:
		    # use your own config library
                    cls._instance.queue.put(
                        pymongo.Connection(*args,**kwargs)[db_name]
                    )
                except:
                    sys.exc_clear()
                    error('Can\'t connect to mongo servers')
 
        return cls._instance     

Example 3

Project: WAPT
Source File: util.py
View license
def CheckClean():
    # Ensure no lingering exceptions - Python should have zero outstanding
    # COM objects
    try:
        sys.exc_clear()
    except AttributeError:
        pass # py3k
    c = _GetInterfaceCount()
    if c:
        print "Warning - %d com interface objects still alive" % c
    c = _GetGatewayCount()
    if c:
        print "Warning - %d com gateway objects still alive" % c

Example 4

Project: TrustRouter
Source File: util.py
View license
def CheckClean():
    # Ensure no lingering exceptions - Python should have zero outstanding
    # COM objects
    try:
        sys.exc_clear()
    except AttributeError:
        pass # py3k
    c = _GetInterfaceCount()
    if c:
        print("Warning - %d com interface objects still alive" % c)
    c = _GetGatewayCount()
    if c:
        print("Warning - %d com gateway objects still alive" % c)

Example 5

Project: fwlite
Source File: os.py
View license
    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 6

Project: fwlite
Source File: _ssl2.py
View license
    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 7

Project: fwlite
Source File: _ssl2.py
View license
    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 8

Project: fwlite
Source File: _ssl2.py
View license
    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 9

Project: cgstudiomap
Source File: backdoor.py
View license
    def _run(self):
        try:
            try:
                console = InteractiveConsole(self.locals)
                # __builtins__ may either be the __builtin__ module or
                # __builtin__.__dict__ in the latter case typing
                # locals() at the backdoor prompt spews out lots of
                # useless stuff
                import __builtin__
                console.locals["__builtins__"] = __builtin__
                console.interact(banner=self.banner)
            except SystemExit:  # raised by quit()
                sys.exc_clear()
        finally:
            self.switch_out()
            self.finalize()

Example 10

Project: cgstudiomap
Source File: os.py
View license
    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, e:
                if e.errno not in ignored_errors:
                    raise
                sys.exc_clear()
            if hub is None:
                hub = get_hub()
                event = hub.loop.io(fd, 1)
            hub.wait(event)

Example 11

Project: cgstudiomap
Source File: os.py
View license
    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, e:
                if e.errno not in ignored_errors:
                    raise
                sys.exc_clear()
            if hub is None:
                hub = get_hub()
                event = hub.loop.io(fd, 2)
            hub.wait(event)

Example 12

Project: cgstudiomap
Source File: _ssl2.py
View license
    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, 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 13

Project: cgstudiomap
Source File: _ssl2.py
View license
    def _sslobj_shutdown(self):
        while True:
            try:
                return self._sslobj.shutdown()
            except SSLError, 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 14

Project: cgstudiomap
Source File: _ssl2.py
View license
    def do_handshake(self):
        """Perform a TLS/SSL handshake."""
        while True:
            try:
                return self._sslobj.do_handshake()
            except SSLError, 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 15

Project: cython
Source File: reraise.py
View license
def test_reraise_error():
    """
    >>> try: test_reraise_error()
    ... except (RuntimeError, TypeError): pass  # Py2, Py3, ...
    ... else: print("FAILED")
    """
    import sys
    if hasattr(sys, 'exc_clear'): # Py2
        sys.exc_clear()
    raise

Example 16

Project: eutester
Source File: qa_account_signup_tests.py
View license
    def test_26a_verify_login_fails(self, newacctadmin): 
        #try to log in, but expect this to fail 
        try:
            gui= self.gui
            gui.driverRestart()
            gui.goLoginPage()
            gui.driver.implicitly_wait(4)
            gui.login(newacctadmin.account, newacctadmin.user, newacctadmin.passwd)
            print("This should have failed!")
        except Exception:
            sys.exc_clear() #clear the current exception
            #This is good
            print("---This is Good, We Expected failure on login here!----")
            pass # continue on
        else:
            raise Exception("Login succeeded where it should have failed")
        finally:
            gui.driver.implicitly_wait(10)

Example 17

Project: floobits-emacs
Source File: exc_fmt.py
View license
    def test2(excp):
        try:
            raise excp
        except Exception as e:
            sys.exc_clear()
            stre = str_e(e)
            assert isinstance(stre, str)
            print(stre)

Example 18

Project: floobits-neovim
Source File: exc_fmt.py
View license
    def test2(excp):
        try:
            raise excp
        except Exception as e:
            sys.exc_clear()
            stre = str_e(e)
            assert isinstance(stre, str)
            print(stre)

Example 19

Project: floobits-sublime
Source File: exc_fmt.py
View license
    def test2(excp):
        try:
            raise excp
        except Exception as e:
            sys.exc_clear()
            stre = str_e(e)
            assert isinstance(stre, str)
            print(stre)

Example 20

Project: floobits-vim
Source File: exc_fmt.py
View license
    def test2(excp):
        try:
            raise excp
        except Exception as e:
            sys.exc_clear()
            stre = str_e(e)
            assert isinstance(stre, str)
            print(stre)

Example 21

Project: flootty
Source File: exc_fmt.py
View license
    def test2(excp):
        try:
            raise excp
        except Exception as e:
            sys.exc_clear()
            stre = str_e(e)
            assert isinstance(stre, str)
            print(stre)

Example 22

Project: mythbox
Source File: runner.py
View license
    def _getDebugger(self):
        dbg = pdb.Pdb()
        try:
            import readline
        except ImportError:
            print "readline module not available"
            sys.exc_clear()
        for path in ('.pdbrc', 'pdbrc'):
            if os.path.exists(path):
                try:
                    rcFile = file(path, 'r')
                except IOError:
                    sys.exc_clear()
                else:
                    dbg.rcLines.extend(rcFile.readlines())
        return dbg

Example 23

Project: mythbox
Source File: runner.py
View license
    def _getDebugger(self):
        dbg = pdb.Pdb()
        try:
            import readline
        except ImportError:
            print "readline module not available"
            sys.exc_clear()
        for path in ('.pdbrc', 'pdbrc'):
            if os.path.exists(path):
                try:
                    rcFile = file(path, 'r')
                except IOError:
                    sys.exc_clear()
                else:
                    dbg.rcLines.extend(rcFile.readlines())
        return dbg

Example 24

Project: PokemonGo-DesktopMap
Source File: os.py
View license
    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 25

Project: PokemonGo-DesktopMap
Source File: os.py
View license
    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 26

Project: PokemonGo-DesktopMap
Source File: _ssl2.py
View license
    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 27

Project: PokemonGo-DesktopMap
Source File: _ssl2.py
View license
    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 28

Project: PokemonGo-DesktopMap
Source File: _ssl2.py
View license
    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 29

Project: PokemonGo-DesktopMap
Source File: _ssl2.py
View license
    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 30

Project: PokemonGo-DesktopMap
Source File: _ssl2.py
View license
    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 31

Project: PokemonGo-DesktopMap
Source File: _ssl2.py
View license
    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 32

Project: PokemonGo-DesktopMap
Source File: os.py
View license
    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 33

Project: PokemonGo-DesktopMap
Source File: os.py
View license
    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 34

Project: PokemonGo-DesktopMap
Source File: _ssl2.py
View license
    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 35

Project: PokemonGo-DesktopMap
Source File: _ssl2.py
View license
    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 36

Project: PokemonGo-DesktopMap
Source File: _ssl2.py
View license
    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 37

Project: PokemonGo-DesktopMap
Source File: _ssl2.py
View license
    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 38

Project: PokemonGo-DesktopMap
Source File: _ssl2.py
View license
    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 39

Project: PokemonGo-DesktopMap
Source File: _ssl2.py
View license
    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 40

Project: SubliminalCollaborator
Source File: runner.py
View license
    def _getDebugger(self):
        dbg = pdb.Pdb()
        try:
            import readline
        except ImportError:
            print "readline module not available"
            sys.exc_clear()
        for path in ('.pdbrc', 'pdbrc'):
            if os.path.exists(path):
                try:
                    rcFile = file(path, 'r')
                except IOError:
                    sys.exc_clear()
                else:
                    dbg.rcLines.extend(rcFile.readlines())
        return dbg

Example 41

Project: SubliminalCollaborator
Source File: runner.py
View license
    def _getDebugger(self):
        dbg = pdb.Pdb()
        try:
            import readline
        except ImportError:
            print "readline module not available"
            sys.exc_clear()
        for path in ('.pdbrc', 'pdbrc'):
            if os.path.exists(path):
                try:
                    rcFile = file(path, 'r')
                except IOError:
                    sys.exc_clear()
                else:
                    dbg.rcLines.extend(rcFile.readlines())
        return dbg

Example 42

Project: flask
Source File: ctx.py
View license
    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 43

Project: pyscale
Source File: pipe.py
View license
def pipe_to_file(pipe, file):
    """Copy items received from *pipe* to *file*"""
    if file.closed:
        return
    
    fcntl.fcntl(file, fcntl.F_SETFL, os.O_NONBLOCK)

    fno = file.fileno()

    try: 
        socket.wait_write(fno)
    except IOError, ex:
        if ex[0] != errno.EPERM:
            raise

        sys.exc_clear()
        use_wait = False
    else:
        use_wait = True

    for chunk in pipe:
        while chunk:
            try:
                written = os.write(fno, chunk)
                chunk = chunk[written:]

            except IOError, ex:
                if ex[0] != errno.EAGAIN:
                    raise
                
                sys.exc_clear()
                
            except OSError, ex:
                if not file.closed:
                    raise
                
                sys.exc_clear()
                pipe.close()
                return
                
            if use_wait: 
                socket.wait_write(fno)
            else:
                gevent.sleep(0)

    file.close()

Example 44

Project: django-s3-cache
Source File: setup.py
View license
def execute_tests():
    """
    Standalone django model test with a 'memory-only-django-installation'.
    You can play with a django model without a complete django app installation.
    http://www.djangosnippets.org/snippets/1044/
    """
    import django

    sys.exc_clear()

    os.environ["DJANGO_SETTINGS_MODULE"] = "django.conf.global_settings"
    from django.conf import global_settings

    global_settings.INSTALLED_APPS = ()
    global_settings.MIDDLEWARE_CLASSES = ()
    global_settings.SECRET_KEY = "not-very-secret"

    global_settings.DATABASES = {
            'default': {
                'ENGINE': 'django.db.backends.sqlite3',
            }
        }

    # http://django.readthedocs.org/en/latest/releases/1.7.html#standalone-scripts
    if django.VERSION >= (1,7):
        django.setup()

    from django.test.utils import get_runner
    test_runner = get_runner(global_settings)

    test_runner = test_runner()
    failures = test_runner.run_tests(['s3cache'])
    sys.exit(failures)

Example 45

Project: Limnoria
Source File: plugin.py
View license
    def upkeep(self, irc, msg, args, level):
        """[<level>]

        Runs the standard upkeep stuff (flushes and gc.collects()).  If given
        a level, runs that level of upkeep (currently, the only supported
        level is "high", which causes the bot to flush a lot of caches as well
        as do normal upkeep stuff).
        """
        L = []
        if level == 'high':
            L.append(format('Regexp cache flushed: %n cleared.',
                            (len(re._cache), 'regexp')))
            re.purge()
            L.append(format('Pattern cache flushed: %n cleared.',
                            (len(ircutils._patternCache), 'compiled pattern')))
            ircutils._patternCache.clear()
            L.append(format('hostmaskPatternEqual cache flushed: %n cleared.',
                            (len(ircutils._hostmaskPatternEqualCache),
                             'result')))
            ircutils._hostmaskPatternEqualCache.clear()
            L.append(format('ircdb username cache flushed: %n cleared.',
                            (len(ircdb.users._nameCache),
                             'username to id mapping')))
            ircdb.users._nameCache.clear()
            L.append(format('ircdb hostmask cache flushed: %n cleared.',
                            (len(ircdb.users._hostmaskCache),
                            'hostmask to id mapping')))
            ircdb.users._hostmaskCache.clear()
            L.append(format('linecache line cache flushed: %n cleared.',
                            (len(linecache.cache), 'line')))
            linecache.clearcache()
            if minisix.PY2:
                sys.exc_clear()
        collected = world.upkeep()
        if gc.garbage:
            L.append('Garbage!  %r.' % gc.garbage)
        L.append(format('%n collected.', (collected, 'object')))
        irc.reply('  '.join(L))

Example 46

Project: Limnoria
Source File: world.py
View license
def upkeep():
    """Does upkeep (like flushing, garbage collection, etc.)"""
    # Just in case, let's clear the exception info.
    try:
        sys.exc_clear()
    except AttributeError:
        # Python 3 does not have sys.exc_clear. The except statement clears
        # the info itself (and we've just entered an except statement)
        pass
    if os.name == 'nt':
        try:
            import msvcrt
            msvcrt.heapmin()
        except ImportError:
            pass
        except IOError: # Win98
            pass
    if conf.daemonized:
        # If we're daemonized, sys.stdout has been replaced with a StringIO
        # object, so let's see if anything's been printed, and if so, let's
        # log.warning it (things shouldn't be printed, and we're more likely
        # to get bug reports if we make it a warning).
        if not hasattr(sys.stdout, 'getvalue'):
            # Stupid twisted sometimes replaces our stdout with theirs, because
            # "The Twisted Way Is The Right Way" (ha!).  So we're stuck simply
            # returning.
            log.warning('Expected cStringIO as stdout, got %r.', sys.stdout)
            return
        s = sys.stdout.getvalue()
        if s:
            log.warning('Printed to stdout after daemonization: %s', s)
            sys.stdout.seek(0)
            sys.stdout.truncate() # Truncates to current offset.
        s = sys.stderr.getvalue()
        if s:
            log.error('Printed to stderr after daemonization: %s', s)
            sys.stderr.seek(0)
            sys.stderr.truncate() # Truncates to current offset.
    doFlush = conf.supybot.flush() and not starting
    if doFlush:
        flush()
        # This is so registry._cache gets filled.
        # This seems dumb, so we'll try not doing it anymore.
        #if registryFilename is not None:
        #    registry.open(registryFilename)
    if not dying:
        if minisix.PY2:
            log.debug('Regexp cache size: %s', len(re._cache))
        log.debug('Pattern cache size: %s', len(ircutils._patternCache))
        log.debug('HostmaskPatternEqual cache size: %s',
                  len(ircutils._hostmaskPatternEqualCache))
        #timestamp = log.timestamp()
        if doFlush:
            log.info('Flushers flushed and garbage collected.')
        else:
            log.info('Garbage collected.')
    collected = gc.collect()
    if gc.garbage:
        log.warning('Noncollectable garbage (file this as a bug on SF.net): %s',
                    gc.garbage)
    return collected

Example 47

Project: pyjs
Source File: ExceptionTest.py
View license
    def testSyntax(self):
        try:
            pass
        except KeyError, e:
            pass
        except (TypeError, LookupError), e:
            pass
        except:
            pass
        finally:
            pass

        try:
            a = 1
        except:
            a = 2
        else:
            a = 3
        finally:
            self.assertEqual(a, 3)
            a = 4
        self.assertEqual(a, 4)

        try:
            a = 11
            raise KeyError('test')
        except:
            a = 12
        else:
            a = 13
        finally:
            self.assertEqual(a, 12)
            a = 14
        self.assertEqual(a, 14)

        try:
            a = 1
        finally:
            a = 2
        self.assertEqual(a, 2)
        try:
            a = 1
            try:
                b = 1
            except:
                b = 2
            else:
                b = 3
            finally:
                self.assertEqual(b, 3)
                b = 4
        except:
            a = 2
        else:
            a = 3
        finally:
            self.assertEqual(a, 3)
            a = 4
        self.assertEqual(a, 4)
        self.assertEqual(b, 4)

        sys.exc_clear()
        try:
            raise
            self.fail("No error raised on 'raise' after 'sys.exc_clear()'")
        except TypeError, e:
            # use message which works for both Python 2.5 and 2.6
            self.assertTrue(e.args[0].startswith('exceptions must be'), e.args[0])
        except:
            e = sys.exc_info()
            self.fail('TypeError expected, got %s' % e[0])

        try:
            raise KeyError, 'test'
            self.fail('No error raised')
        except KeyError, e:
            self.assertEqual(e.args[0], 'test')
        except:
            e = sys.exc_info()
            self.fail('KeyError expected, got %s' % e[0])
            e = e[1]

        try:
            raise
        except:
            err = sys.exc_info()
            self.assertEqual(e.args[0], err[1].args[0])

        raise_errors = [KeyError('KeyError'), TypeError('TypeError'),
                        AttributeError('AttributeError'),
                        LookupError('LookupError')]
        raised_errors = []
        for err in raise_errors:
            try:
                raise err
                self.fail("Failed to raise exception")
            except (KeyError, TypeError), e1:
                raised_errors.append(e1)
                if isinstance(e1, KeyError):
                    self.assertEqual(e1.args[0], 'KeyError')
                elif isinstance(e1, TypeError):
                    self.assertEqual(e1.args[0], 'TypeError')
                else:
                    self.fail('neither KeyError nor TypeError in except (KeyError, TypeError)')
            except AttributeError, e2:
                raised_errors.append(e2)
                self.assertEqual(e2.args[0], 'AttributeError')
            except:
                e3 = sys.exc_info()[1]
                raised_errors.append(e3)
                self.assertEqual(e3.args[0], 'LookupError')
        self.assertEqual(len(raised_errors), len(raise_errors))

        try:
            try:
                raise TypeError('TypeError')
            except KeyError, e:
                self.fail("Got KeyError")
            self.fail("TypeError should not be ignored")
        except TypeError, e:
            self.assertEqual(e.args[0], 'TypeError')

Example 48

Project: pyload
Source File: PluginThread.py
View license
    def run(self):
        """run method"""
        pyfile = None

        while True:
            del pyfile
            self.active = self.queue.get()
            pyfile = self.active

            if self.active == "quit":
                self.active = False
                self.m.threads.remove(self)
                return True

            try:
                if not pyfile.hasPlugin(): continue
                #this pyfile was deleted while queueing

                pyfile.plugin.checkForSameFiles(starting=True)
                self.m.log.info(_("Download starts: %s" % pyfile.name))

                # start download
                self.m.core.hookManager.downloadPreparing(pyfile)
                pyfile.plugin.preprocessing(self)

                self.m.log.info(_("Download finished: %s") % pyfile.name)
                self.m.core.hookManager.downloadFinished(pyfile)
                self.m.core.files.checkPackageFinished(pyfile)

            except NotImplementedError:
                self.m.log.error(_("Plugin %s is missing a function.") % pyfile.pluginname)
                pyfile.setStatus("failed")
                pyfile.error = "Plugin does not work"
                self.clean(pyfile)
                continue

            except Abort:
                try:
                    self.m.log.info(_("Download aborted: %s") % pyfile.name)
                except:
                    pass

                pyfile.setStatus("aborted")

                self.clean(pyfile)
                continue

            except Reconnect:
                self.queue.put(pyfile)
                #pyfile.req.clearCookies()

                while self.m.reconnecting.isSet():
                    sleep(0.5)

                continue

            except Retry, e:
                reason = e.args[0]
                self.m.log.info(_("Download restarted: %(name)s | %(msg)s") % {"name": pyfile.name, "msg": reason})
                self.queue.put(pyfile)
                continue

            except Fail, e:
                msg = e.args[0]

                if msg == "offline":
                    pyfile.setStatus("offline")
                    self.m.log.warning(_("Download is offline: %s") % pyfile.name)
                elif msg == "temp. offline":
                    pyfile.setStatus("temp. offline")
                    self.m.log.warning(_("Download is temporary offline: %s") % pyfile.name)
                else:
                    pyfile.setStatus("failed")
                    self.m.log.warning(_("Download failed: %(name)s | %(msg)s") % {"name": pyfile.name, "msg": msg})
                    pyfile.error = msg

                self.m.core.hookManager.downloadFailed(pyfile)
                self.clean(pyfile)
                continue

            except error, e:
                if len(e.args) == 2:
                    code, msg = e.args
                else:
                    code = 0
                    msg = e.args

                self.m.log.debug("pycurl exception %s: %s" % (code, msg))

                if code in (7, 18, 28, 52, 56):
                    self.m.log.warning(_("Couldn't connect to host or connection reset, waiting 1 minute and retry."))
                    wait = time() + 60

                    pyfile.waitUntil = wait
                    pyfile.setStatus("waiting")
                    while time() < wait:
                        sleep(1)
                        if pyfile.abort:
                            break

                    if pyfile.abort:
                        self.m.log.info(_("Download aborted: %s") % pyfile.name)
                        pyfile.setStatus("aborted")

                        self.clean(pyfile)
                    else:
                        self.queue.put(pyfile)

                    continue

                else:
                    pyfile.setStatus("failed")
                    self.m.log.error("pycurl error %s: %s" % (code, msg))
                    if self.m.core.debug:
                        print_exc()
                        self.writeDebugReport(pyfile)

                    self.m.core.hookManager.downloadFailed(pyfile)

                self.clean(pyfile)
                continue

            except SkipDownload, e:
                pyfile.setStatus("skipped")

                self.m.log.info(
                    _("Download skipped: %(name)s due to %(plugin)s") % {"name": pyfile.name, "plugin": e.message})

                self.clean(pyfile)

                self.m.core.files.checkPackageFinished(pyfile)

                self.active = False
                self.m.core.files.save()

                continue


            except Exception, e:
                pyfile.setStatus("failed")
                self.m.log.warning(_("Download failed: %(name)s | %(msg)s") % {"name": pyfile.name, "msg": str(e)})
                pyfile.error = str(e)

                if self.m.core.debug:
                    print_exc()
                    self.writeDebugReport(pyfile)

                self.m.core.hookManager.downloadFailed(pyfile)
                self.clean(pyfile)
                continue

            finally:
                self.m.core.files.save()
                pyfile.checkIfProcessed()
                exc_clear()

            
            #pyfile.plugin.req.clean()

            self.active = False
            pyfile.finishIfDone()
            self.m.core.files.save()

Example 49

Project: pyload
Source File: PluginThread.py
View license
    def run(self):
        """run method"""

        pyfile = self.active
        retry = False

        try:
            self.m.log.info(_("Decrypting starts: %s") % self.active.name)
            self.active.plugin.preprocessing(self)

        except NotImplementedError:
            self.m.log.error(_("Plugin %s is missing a function.") % self.active.pluginname)
            return

        except Fail, e:
            msg = e.args[0]

            if msg == "offline":
                self.active.setStatus("offline")
                self.m.log.warning(_("Download is offline: %s") % self.active.name)
            else:
                self.active.setStatus("failed")
                self.m.log.error(_("Decrypting failed: %(name)s | %(msg)s") % {"name": self.active.name, "msg": msg})
                self.active.error = msg

            return

        except Abort:
            self.m.log.info(_("Download aborted: %s") % pyfile.name)
            pyfile.setStatus("aborted")

            return

        except Retry:
            self.m.log.info(_("Retrying %s") % self.active.name)
            retry = True
            return self.run()

        except Exception, e:
            self.active.setStatus("failed")
            self.m.log.error(_("Decrypting failed: %(name)s | %(msg)s") % {"name": self.active.name, "msg": str(e)})
            self.active.error = str(e)

            if self.m.core.debug:
                print_exc()
                self.writeDebugReport(pyfile)

            return


        finally:
            if not retry:
                self.active.release()
                self.active = False
                self.m.core.files.save()
                self.m.localThreads.remove(self)
                exc_clear()


        #self.m.core.hookManager.downloadFinished(pyfile)


        #self.m.localThreads.remove(self)
        #self.active.finishIfDone()
        if not retry:
            pyfile.delete()

Example 50

Project: pymo
Source File: test_py3kwarn.py
View license
    def test_sys_exc_clear(self):
        expected = 'sys.exc_clear() not supported in 3.x; use except clauses'
        with check_py3k_warnings() as w:
            self.assertWarning(sys.exc_clear(), w, expected)