Python socket.timeout() Examples

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

Example 1
Project: pycos   Author: pgiri   File: netpycos.py    (license) View Source Project 7 votes vote down vote up
def __call__(self, *args, **kwargs):
        """Must be used with 'yeild' as 'rtask = yield rti(*args, **kwargs)'.

        Run RTI (method at remote location) with args and kwargs. Both args and
        kwargs must be serializable. Result is (remote) Task instance if call
        succeeds, otherwise it is None.
        """
        req = _NetRequest('run_rti', kwargs={'name': self._name, 'args': args, 'kwargs': kwargs,
                                             'mid': self._mid},
                          dst=self._location, timeout=MsgTimeout)
        reply = yield _Peer._sync_reply(req)
        if isinstance(reply, Task):
            raise StopIteration(reply)
        elif reply is None:
            raise StopIteration(None)
        else:
            raise Exception(reply) 
Example 2
Project: pycos   Author: pgiri   File: __init__.py    (license) View Source Project 7 votes vote down vote up
def _timed_out(self):
                if self._rsock and self._rsock.type & socket.SOCK_STREAM:
                    if self._read_overlap or self._write_overlap:
                        win32file.CancelIo(self._fileno)
                if self._read_task:
                    if self._rsock and self._rsock.type & socket.SOCK_DGRAM:
                        self._notifier.clear(self, _AsyncPoller._Read)
                        self._read_fn = None
                    self._read_task.throw(socket.timeout('timed out'))
                    self._read_result = self._read_task = None
                if self._write_task:
                    if self._rsock and self._rsock.type & socket.SOCK_DGRAM:
                        self._notifier.clear(self, _AsyncPoller._Write)
                        self._write_fn = None
                    self._write_task.throw(socket.timeout('timed out'))
                    self._write_result = self._write_task = None 
Example 3
Project: pycos   Author: pgiri   File: __init__.py    (license) View Source Project 7 votes vote down vote up
def wait(self, timeout=None):
        """Must be used with 'yield' as 'yield event.wait()' .
        """
        if self._flag:
            raise StopIteration(True)
        if not self._scheduler:
            self._scheduler = Pycos.scheduler()
        task = Pycos.cur_task(self._scheduler)
        if timeout is not None:
            if timeout <= 0:
                raise StopIteration(False)
        self._waitlist.append(task)
        if (yield task._await_(timeout)) is None:
            try:
                self._waitlist.remove(task)
            except ValueError:
                pass
            raise StopIteration(False)
        else:
            raise StopIteration(True) 
Example 4
Project: pycos   Author: pgiri   File: netpycos.py    (license) View Source Project 6 votes vote down vote up
def close_peer(self, location, timeout=MsgTimeout):
        """Must be used with 'yield', as
        'yield scheduler.close_peer("loc")'.

        Close peer at 'location'.
        """
        if isinstance(location, Location):
            _Peer._lock.acquire()
            peer = _Peer.peers.get((location.addr, location.port), None)
            _Peer._lock.release()
            if peer:

                def sys_proc(peer, timeout, done, task=None):
                    yield _Peer.close_peer(peer, timeout=timeout, task=task)
                    done.set()

                event = Event()
                SysTask(sys_proc, peer, timeout, event)
                yield event.wait() 
Example 5
Project: pycos   Author: pgiri   File: netpycos.py    (license) View Source Project 6 votes vote down vote up
def del_file(self, location, file, dir=None, timeout=None):
        """Must be used with 'yield' as
        'loc = yield scheduler.del_file(location, "file1")'.

        Delete 'file' from peer at 'location'. 'dir' must be same as that used
        for 'send_file'.
        """
        if isinstance(dir, basestring) and dir:
            dir = dir.strip()
            # reject absolute path for dir
            if os.path.join(os.sep, dir) == dir:
                raise StopIteration(-1)
        kwargs = {'file': os.path.basename(file), 'dir': dir}
        req = _NetRequest('del_file', kwargs=kwargs, dst=location, timeout=timeout)
        reply = yield _Peer._sync_reply(req)
        if reply is None:
            reply = -1
        raise StopIteration(reply) 
Example 6
Project: pycos   Author: pgiri   File: netpycos.py    (license) View Source Project 6 votes vote down vote up
def locate(name, location=None, timeout=None):
        """Must be used with 'yield' as 'rti = yield RTI.locate("name")'.

        Returns RTI instance to registered RTI at a remote peer so its method
        can be used to execute tasks at that peer.

        If 'location' is given, RTI is looked up at that specific peer;
        otherwise, all known peers are queried for given name.
        """
        if not RTI._pycos:
            RTI._pycos = Pycos.instance()
        req = _NetRequest('locate_rti', kwargs={'name': name}, dst=location, timeout=timeout)
        req.event = Event()
        req_id = id(req)
        RTI._pycos._lock.acquire()
        RTI._pycos._pending_reqs[req_id] = req
        RTI._pycos._lock.release()
        _Peer.send_req_to(req, location)
        if (yield req.event.wait(timeout)) is False:
            req.reply = None
        rti = req.reply
        RTI._pycos._lock.acquire()
        RTI._pycos._pending_reqs.pop(req_id, None)
        RTI._pycos._lock.release()
        raise StopIteration(rti) 
Example 7
Project: pycos   Author: pgiri   File: netpycos.py    (license) View Source Project 6 votes vote down vote up
def monitor(self, task, timeout=MsgTimeout):
        """Must be used with 'yeild' as 'reply = yield rti.monitor(task)'.

        Install 'task' (a Task instance) as monitor for tasks created; i.e.,
        'task' receives MonitorException messages. If call is successful, the
        result is 0.
        """
        if not isinstance(task, Task) and monitor is not None:
            raise StopIteration(-1)
        if self._mid:
            mid = self._mid
        else:
            mid = RTI._pycos._location
        req = _NetRequest('rti_monitor', kwargs={'name': self._name, 'monitor': task, 'mid': mid},
                          dst=self._location, timeout=timeout)
        reply = yield _Peer._sync_reply(req)
        if reply == 0:
            self._mid = mid
        raise StopIteration(reply) 
Example 8
Project: pycos   Author: pgiri   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def send(self, message):
        """May be used with 'yield'. Sends 'message' to task.

        If task is currently waiting with 'receive', it is resumed with
        'message'. Otherwise, 'message' is queued so that next receive call will
        return message.

        Can also be used on remotely running tasks.
        """
        if self._location:
            request = _NetRequest('send', kwargs={'message': message, 'name': self._name,
                                                  'task': self._id},
                                  dst=self._location, timeout=MsgTimeout)
            # request is queued for asynchronous processing
            if _Peer.send_req(request) != 0:
                logger.warning('remote task at %s may not be valid', self._location)
                return -1
            else:
                return 0
        else:
            return self._scheduler._resume(self, message, Pycos._AwaitMsg_) 
Example 9
Project: pycos   Author: pgiri   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def deliver(self, message, timeout=None):
        """Must be used with 'yield' as 'yield task.deliver(message)'.

        Can also be used on remotely running tasks.

        Return value indicates status of delivering the message: If it is 1,
        then message has been delivered, if it is 0, it couldn't be delivered
        before timeout, and if it is < 0, then the (remote) task is not valid.
        """
        if self._location:
            request = _NetRequest('deliver', kwargs={'message': message, 'name': self._name,
                                                     'task': self._id},
                                  dst=self._location, timeout=timeout)
            request.reply = -1
            reply = yield _Peer._sync_reply(request, alarm_value=0)
            if reply is None:
                reply = -1
            # if reply < 0:
            #     logger.warning('remote task at %s may not be valid', self._location)
        else:
            reply = self._scheduler._resume(self, message, Pycos._AwaitMsg_)
            if reply == 0:
                reply = 1
        raise StopIteration(reply) 
Example 10
Project: pycos   Author: pgiri   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def value(self, timeout=None):
        """Get last value 'yield'ed / value of StopIteration of task.

        NB: This method should _not_ be called from a task! This method is meant
        for main thread in the user program to wait for (main) task(s) it
        creates.

        Once task stops (finishes) executing, the last value is returned.
        """
        value = None
        self._scheduler._lock.acquire()
        if self._complete is None:
            self._complete = threading.Event()
            self._scheduler._lock.release()
            if self._complete.wait(timeout=timeout) is True:
                value = self._value
        elif self._complete == 0:
            self._scheduler._lock.release()
            value = self._value
        else:
            self._scheduler._lock.release()
            if self._complete.wait(timeout=timeout) is True:
                value = self._value
        return value 
Example 11
Project: pycos   Author: pgiri   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def terminate(self):
        """Terminate task.

        If this method called by a thread (and not a task), there is a chance
        that task being terminated is currently running and can interfere with
        GenratorExit exception that will be thrown to task.

        Can also be used on remotely running tasks.
        """
        if self._location:
            request = _NetRequest('terminate_task', kwargs={'task': self._id, 'name': self._name},
                                  dst=self._location, timeout=MsgTimeout)
            if _Peer.send_req(request) != 0:
                logger.warning('remote task at %s may not be valid', self._location)
                return -1
            return 0
        else:
            return self._scheduler._terminate_task(self) 
Example 12
Project: pycos   Author: pgiri   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def monitor(self, observe):
        """Must be used with 'yield' as 'yield task.monitor(observe)', where
        'observe' is a task which will be monitored by 'task'.  When 'observe'
        is finished (raises StopIteration or terminated due to uncaught
        exception), that exception is sent as a message to 'task' (monitor
        task).

        Monitor can inspect the exception and restart observed task if
        necessary. 'observe' can be a remote task.

        Can also be used on remotely running 'observe' task.
        """
        if observe._location:
            # remote task
            request = _NetRequest('monitor', kwargs={'monitor': self, 'name': observe._name,
                                                     'task': observe._id},
                                  dst=observe._location, timeout=MsgTimeout)
            reply = yield _Peer._sync_reply(request)
        else:
            reply = self._scheduler._monitor(self, observe)
        raise StopIteration(reply) 
Example 13
Project: pycos   Author: pgiri   File: netpycos.py    (license) View Source Project 6 votes vote down vote up
def close_peer(self, location, timeout=MsgTimeout):
        """Must be used with 'yield', as
        'yield scheduler.close_peer("loc")'.

        Close peer at 'location'.
        """
        if isinstance(location, Location):
            _Peer._lock.acquire()
            peer = _Peer.peers.get((location.addr, location.port), None)
            _Peer._lock.release()
            if peer:

                def sys_proc(peer, timeout, done, task=None):
                    yield _Peer.close_peer(peer, timeout=timeout, task=task)
                    done.set()

                event = Event()
                SysTask(sys_proc, peer, timeout, event)
                yield event.wait() 
Example 14
Project: pycos   Author: pgiri   File: netpycos.py    (license) View Source Project 6 votes vote down vote up
def del_file(self, location, file, dir=None, timeout=None):
        """Must be used with 'yield' as
        'loc = yield scheduler.del_file(location, "file1")'.

        Delete 'file' from peer at 'location'. 'dir' must be same as that used
        for 'send_file'.
        """
        if isinstance(dir, str) and dir:
            dir = dir.strip()
            # reject absolute path for dir
            if os.path.join(os.sep, dir) == dir:
                raise StopIteration(-1)
        kwargs = {'file': os.path.basename(file), 'dir': dir}
        req = _NetRequest('del_file', kwargs=kwargs, dst=location, timeout=timeout)
        reply = yield _Peer._sync_reply(req)
        if reply is None:
            reply = -1
        raise StopIteration(reply) 
Example 15
Project: pycos   Author: pgiri   File: netpycos.py    (license) View Source Project 6 votes vote down vote up
def locate(name, location=None, timeout=None):
        """Must be used with 'yield' as 'rti = yield RTI.locate("name")'.

        Returns RTI instance to registered RTI at a remote peer so its method
        can be used to execute tasks at that peer.

        If 'location' is given, RTI is looked up at that specific peer;
        otherwise, all known peers are queried for given name.
        """
        if not RTI._pycos:
            RTI._pycos = Pycos.instance()
        req = _NetRequest('locate_rti', kwargs={'name': name}, dst=location, timeout=timeout)
        req.event = Event()
        req_id = id(req)
        RTI._pycos._lock.acquire()
        RTI._pycos._pending_reqs[req_id] = req
        RTI._pycos._lock.release()
        _Peer.send_req_to(req, location)
        if (yield req.event.wait(timeout)) is False:
            req.reply = None
        rti = req.reply
        RTI._pycos._lock.acquire()
        RTI._pycos._pending_reqs.pop(req_id, None)
        RTI._pycos._lock.release()
        raise StopIteration(rti) 
Example 16
Project: pycos   Author: pgiri   File: netpycos.py    (license) View Source Project 6 votes vote down vote up
def monitor(self, task, timeout=MsgTimeout):
        """Must be used with 'yeild' as 'reply = yield rti.monitor(task)'.

        Install 'task' (a Task instance) as monitor for tasks created; i.e.,
        'task' receives MonitorException messages. If call is successful, the
        result is 0.
        """
        if not isinstance(task, Task) and monitor is not None:
            raise StopIteration(-1)
        if self._mid:
            mid = self._mid
        else:
            mid = RTI._pycos._location
        req = _NetRequest('rti_monitor', kwargs={'name': self._name, 'monitor': task, 'mid': mid},
                          dst=self._location, timeout=timeout)
        reply = yield _Peer._sync_reply(req)
        if reply == 0:
            self._mid = mid
        raise StopIteration(reply) 
Example 17
Project: pycos   Author: pgiri   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def wait(self, timeout=None):
        """Must be used with 'yield' as 'yield event.wait()' .
        """
        if self._flag:
            raise StopIteration(True)
        if not self._scheduler:
            self._scheduler = Pycos.scheduler()
        task = Pycos.cur_task(self._scheduler)
        if timeout is not None:
            if timeout <= 0:
                raise StopIteration(False)
        self._waitlist.append(task)
        if (yield task._await_(timeout)) is None:
            try:
                self._waitlist.remove(task)
            except ValueError:
                pass
            raise StopIteration(False)
        else:
            raise StopIteration(True) 
Example 18
Project: pycos   Author: pgiri   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def send(self, message):
        """May be used with 'yield'. Sends 'message' to task.

        If task is currently waiting with 'receive', it is resumed with
        'message'. Otherwise, 'message' is queued so that next receive call will
        return message.

        Can also be used on remotely running tasks.
        """
        if self._location:
            request = _NetRequest('send', kwargs={'message': message, 'name': self._name,
                                                  'task': self._id},
                                  dst=self._location, timeout=MsgTimeout)
            # request is queued for asynchronous processing
            if _Peer.send_req(request) != 0:
                logger.warning('remote task at %s may not be valid', self._location)
                return -1
            else:
                return 0
        else:
            return self._scheduler._resume(self, message, Pycos._AwaitMsg_) 
Example 19
Project: pycos   Author: pgiri   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def deliver(self, message, timeout=None):
        """Must be used with 'yield' as 'yield task.deliver(message)'.

        Can also be used on remotely running tasks.

        Return value indicates status of delivering the message: If it is 1,
        then message has been delivered, if it is 0, it couldn't be delivered
        before timeout, and if it is < 0, then the (remote) task is not valid.
        """
        if self._location:
            request = _NetRequest('deliver', kwargs={'message': message, 'name': self._name,
                                                     'task': self._id},
                                  dst=self._location, timeout=timeout)
            request.reply = -1
            reply = yield _Peer._sync_reply(request, alarm_value=0)
            if reply is None:
                reply = -1
            # if reply < 0:
            #     logger.warning('remote task at %s may not be valid', self._location)
        else:
            reply = self._scheduler._resume(self, message, Pycos._AwaitMsg_)
            if reply == 0:
                reply = 1
        raise StopIteration(reply) 
Example 20
Project: pycos   Author: pgiri   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def finish(self, timeout=None):
        """Get last value 'yield'ed / value of StopIteration of task. Must be
        used in a task with 'yield' as 'value = yield other_task.finish()'

        Once task stops (finishes) executing, the last value is returned.
        """
        value = None
        if self._complete is None:
            self._complete = Event()
            if (yield self._complete.wait(timeout=timeout)) is True:
                value = self._value
        elif self._complete == 0:
            value = self._value
        elif isinstance(self._complete, Event):
            if (yield self._complete.wait(timeout=timeout)) is True:
                value = self._value
        else:
            raise RuntimeError('invalid wait on %s/%s: %s' %
                               (self._name, self._id, type(self._complete)))
        raise StopIteration(value) 
Example 21
Project: pycos   Author: pgiri   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def terminate(self):
        """Terminate task.

        If this method called by a thread (and not a task), there is a chance
        that task being terminated is currently running and can interfere with
        GenratorExit exception that will be thrown to task.

        Can also be used on remotely running tasks.
        """
        if self._location:
            request = _NetRequest('terminate_task', kwargs={'task': self._id, 'name': self._name},
                                  dst=self._location, timeout=MsgTimeout)
            if _Peer.send_req(request) != 0:
                logger.warning('remote task at %s may not be valid', self._location)
                return -1
            return 0
        else:
            return self._scheduler._terminate_task(self) 
Example 22
Project: pycos   Author: pgiri   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def monitor(self, observe):
        """Must be used with 'yield' as 'yield task.monitor(observe)', where
        'observe' is a task which will be monitored by 'task'.  When 'observe'
        is finished (raises StopIteration or terminated due to uncaught
        exception), that exception is sent as a message to 'task' (monitor
        task).

        Monitor can inspect the exception and restart observed task if
        necessary. 'observe' can be a remote task.

        Can also be used on remotely running 'observe' task.
        """
        if observe._location:
            # remote task
            request = _NetRequest('monitor', kwargs={'monitor': self, 'name': observe._name,
                                                     'task': observe._id},
                                  dst=observe._location, timeout=MsgTimeout)
            reply = yield _Peer._sync_reply(request)
        else:
            reply = self._scheduler._monitor(self, observe)
        raise StopIteration(reply) 
Example 23
Project: pyOSC3   Author: Qirky   File: OSC3.py    (license) View Source Project 6 votes vote down vote up
def _receiveWithTimeout(self, count):
		chunk = str()
		while len(chunk) < count:
			try:
				tmp = self.socket.recv(count - len(chunk))
			except socket.timeout:
				if not self._running:
					print("CLIENT: Socket timed out and termination requested.")
					return None
				else:
					continue
			except socket.error as e:
				if e[0] == errno.ECONNRESET:
					print("CLIENT: Connection reset by peer.")
					return None
				else:
					raise e
			if not tmp or len(tmp) == 0:
				print("CLIENT: Socket has been closed.")
				return None
			chunk = chunk + tmp
		return chunk 
Example 24
Project: pyOSC3   Author: Qirky   File: OSC2.py    (license) View Source Project 6 votes vote down vote up
def _receiveWithTimeout(self, count):
		chunk = str()
		while len(chunk) < count:
			try:
				tmp = self.socket.recv(count - len(chunk))
			except socket.timeout:
				if not self._running:
					print "CLIENT: Socket timed out and termination requested."
					return None
				else:
					continue
			except socket.error, e:
				if e[0] == errno.ECONNRESET:
					print "CLIENT: Connection reset by peer."
					return None
				else:
					raise e
			if not tmp or len(tmp) == 0:
				print "CLIENT: Socket has been closed."
				return None
			chunk = chunk + tmp
		return chunk 
Example 25
Project: python-   Author: secondtonone1   File: pyopenssl.py    (license) View Source Project 6 votes vote down vote up
def recv(self, *args, **kwargs):
        try:
            data = self.connection.recv(*args, **kwargs)
        except OpenSSL.SSL.SysCallError as e:
            if self.suppress_ragged_eofs and e.args == (-1, 'Unexpected EOF'):
                return b''
            else:
                raise SocketError(str(e))
        except OpenSSL.SSL.ZeroReturnError as e:
            if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN:
                return b''
            else:
                raise
        except OpenSSL.SSL.WantReadError:
            rd, wd, ed = select.select(
                [self.socket], [], [], self.socket.gettimeout())
            if not rd:
                raise timeout('The read operation timed out')
            else:
                return self.recv(*args, **kwargs)
        else:
            return data 
Example 26
Project: python-   Author: secondtonone1   File: pyopenssl.py    (license) View Source Project 6 votes vote down vote up
def recv_into(self, *args, **kwargs):
        try:
            return self.connection.recv_into(*args, **kwargs)
        except OpenSSL.SSL.SysCallError as e:
            if self.suppress_ragged_eofs and e.args == (-1, 'Unexpected EOF'):
                return 0
            else:
                raise SocketError(str(e))
        except OpenSSL.SSL.ZeroReturnError as e:
            if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN:
                return 0
            else:
                raise
        except OpenSSL.SSL.WantReadError:
            rd, wd, ed = select.select(
                [self.socket], [], [], self.socket.gettimeout())
            if not rd:
                raise timeout('The read operation timed out')
            else:
                return self.recv_into(*args, **kwargs) 
Example 27
Project: python-   Author: secondtonone1   File: connectionpool.py    (license) View Source Project 6 votes vote down vote up
def _raise_timeout(self, err, url, timeout_value):
        """Is the error actually a timeout? Will raise a ReadTimeout or pass"""

        if isinstance(err, SocketTimeout):
            raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value)

        # See the above comment about EAGAIN in Python 3. In Python 2 we have
        # to specifically catch it and throw the timeout error
        if hasattr(err, 'errno') and err.errno in _blocking_errnos:
            raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value)

        # Catch possible read timeouts thrown as SSL errors. If not the
        # case, rethrow the original. We need to do this because of:
        # http://bugs.python.org/issue10272
        if 'timed out' in str(err) or 'did not complete (read)' in str(err):  # Python 2.6
            raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value) 
Example 28
Project: my-first-blog   Author: AnkurBegining   File: securetransport.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, socket):
        self.socket = socket
        self.context = None
        self._makefile_refs = 0
        self._closed = False
        self._exception = None
        self._keychain = None
        self._keychain_dir = None
        self._client_cert_chain = None

        # We save off the previously-configured timeout and then set it to
        # zero. This is done because we use select and friends to handle the
        # timeouts, but if we leave the timeout set on the lower socket then
        # Python will "kindly" call select on that socket again for us. Avoid
        # that by forcing the timeout to zero.
        self._timeout = self.socket.gettimeout()
        self.socket.settimeout(0) 
Example 29
Project: my-first-blog   Author: AnkurBegining   File: pyopenssl.py    (license) View Source Project 6 votes vote down vote up
def recv(self, *args, **kwargs):
        try:
            data = self.connection.recv(*args, **kwargs)
        except OpenSSL.SSL.SysCallError as e:
            if self.suppress_ragged_eofs and e.args == (-1, 'Unexpected EOF'):
                return b''
            else:
                raise SocketError(str(e))
        except OpenSSL.SSL.ZeroReturnError as e:
            if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN:
                return b''
            else:
                raise
        except OpenSSL.SSL.WantReadError:
            rd = util.wait_for_read(self.socket, self.socket.gettimeout())
            if not rd:
                raise timeout('The read operation timed out')
            else:
                return self.recv(*args, **kwargs)
        else:
            return data 
Example 30
Project: my-first-blog   Author: AnkurBegining   File: pyopenssl.py    (license) View Source Project 6 votes vote down vote up
def recv_into(self, *args, **kwargs):
        try:
            return self.connection.recv_into(*args, **kwargs)
        except OpenSSL.SSL.SysCallError as e:
            if self.suppress_ragged_eofs and e.args == (-1, 'Unexpected EOF'):
                return 0
            else:
                raise SocketError(str(e))
        except OpenSSL.SSL.ZeroReturnError as e:
            if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN:
                return 0
            else:
                raise
        except OpenSSL.SSL.WantReadError:
            rd = util.wait_for_read(self.socket, self.socket.gettimeout())
            if not rd:
                raise timeout('The read operation timed out')
            else:
                return self.recv_into(*args, **kwargs) 
Example 31
Project: my-first-blog   Author: AnkurBegining   File: connectionpool.py    (license) View Source Project 6 votes vote down vote up
def _raise_timeout(self, err, url, timeout_value):
        """Is the error actually a timeout? Will raise a ReadTimeout or pass"""

        if isinstance(err, SocketTimeout):
            raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value)

        # See the above comment about EAGAIN in Python 3. In Python 2 we have
        # to specifically catch it and throw the timeout error
        if hasattr(err, 'errno') and err.errno in _blocking_errnos:
            raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value)

        # Catch possible read timeouts thrown as SSL errors. If not the
        # case, rethrow the original. We need to do this because of:
        # http://bugs.python.org/issue10272
        if 'timed out' in str(err) or 'did not complete (read)' in str(err):  # Python 2.6
            raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value) 
Example 32
Project: my-first-blog   Author: AnkurBegining   File: pyopenssl.py    (license) View Source Project 6 votes vote down vote up
def recv(self, *args, **kwargs):
        try:
            data = self.connection.recv(*args, **kwargs)
        except OpenSSL.SSL.SysCallError as e:
            if self.suppress_ragged_eofs and e.args == (-1, 'Unexpected EOF'):
                return b''
            else:
                raise SocketError(str(e))
        except OpenSSL.SSL.ZeroReturnError as e:
            if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN:
                return b''
            else:
                raise
        except OpenSSL.SSL.WantReadError:
            rd, wd, ed = select.select(
                [self.socket], [], [], self.socket.gettimeout())
            if not rd:
                raise timeout('The read operation timed out')
            else:
                return self.recv(*args, **kwargs)
        else:
            return data 
Example 33
Project: my-first-blog   Author: AnkurBegining   File: pyopenssl.py    (license) View Source Project 6 votes vote down vote up
def recv_into(self, *args, **kwargs):
        try:
            return self.connection.recv_into(*args, **kwargs)
        except OpenSSL.SSL.SysCallError as e:
            if self.suppress_ragged_eofs and e.args == (-1, 'Unexpected EOF'):
                return 0
            else:
                raise SocketError(str(e))
        except OpenSSL.SSL.ZeroReturnError as e:
            if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN:
                return 0
            else:
                raise
        except OpenSSL.SSL.WantReadError:
            rd, wd, ed = select.select(
                [self.socket], [], [], self.socket.gettimeout())
            if not rd:
                raise timeout('The read operation timed out')
            else:
                return self.recv_into(*args, **kwargs) 
Example 34
Project: my-first-blog   Author: AnkurBegining   File: connectionpool.py    (license) View Source Project 6 votes vote down vote up
def _raise_timeout(self, err, url, timeout_value):
        """Is the error actually a timeout? Will raise a ReadTimeout or pass"""

        if isinstance(err, SocketTimeout):
            raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value)

        # See the above comment about EAGAIN in Python 3. In Python 2 we have
        # to specifically catch it and throw the timeout error
        if hasattr(err, 'errno') and err.errno in _blocking_errnos:
            raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value)

        # Catch possible read timeouts thrown as SSL errors. If not the
        # case, rethrow the original. We need to do this because of:
        # http://bugs.python.org/issue10272
        if 'timed out' in str(err) or 'did not complete (read)' in str(err):  # Python 2.6
            raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value) 
Example 35
Project: gimel   Author: Alephbet   File: connection.py    (MIT License) View Source Project 6 votes vote down vote up
def send_packed_command(self, command):
        "Send an already packed command to the Redis server"
        if not self._sock:
            self.connect()
        try:
            if isinstance(command, str):
                command = [command]
            for item in command:
                self._sock.sendall(item)
        except socket.timeout:
            self.disconnect()
            raise TimeoutError("Timeout writing to socket")
        except socket.error:
            e = sys.exc_info()[1]
            self.disconnect()
            if len(e.args) == 1:
                errno, errmsg = 'UNKNOWN', e.args[0]
            else:
                errno = e.args[0]
                errmsg = e.args[1]
            raise ConnectionError("Error %s while writing to socket. %s." %
                                  (errno, errmsg))
        except:
            self.disconnect()
            raise 
Example 36
Project: googletranslate.popclipext   Author: wizyoung   File: securetransport.py    (MIT License) View Source Project 6 votes vote down vote up
def __init__(self, socket):
        self.socket = socket
        self.context = None
        self._makefile_refs = 0
        self._closed = False
        self._exception = None
        self._keychain = None
        self._keychain_dir = None
        self._client_cert_chain = None

        # We save off the previously-configured timeout and then set it to
        # zero. This is done because we use select and friends to handle the
        # timeouts, but if we leave the timeout set on the lower socket then
        # Python will "kindly" call select on that socket again for us. Avoid
        # that by forcing the timeout to zero.
        self._timeout = self.socket.gettimeout()
        self.socket.settimeout(0) 
Example 37
Project: googletranslate.popclipext   Author: wizyoung   File: pyopenssl.py    (MIT License) View Source Project 6 votes vote down vote up
def recv(self, *args, **kwargs):
        try:
            data = self.connection.recv(*args, **kwargs)
        except OpenSSL.SSL.SysCallError as e:
            if self.suppress_ragged_eofs and e.args == (-1, 'Unexpected EOF'):
                return b''
            else:
                raise SocketError(str(e))
        except OpenSSL.SSL.ZeroReturnError as e:
            if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN:
                return b''
            else:
                raise
        except OpenSSL.SSL.WantReadError:
            rd = util.wait_for_read(self.socket, self.socket.gettimeout())
            if not rd:
                raise timeout('The read operation timed out')
            else:
                return self.recv(*args, **kwargs)
        else:
            return data 
Example 38
Project: googletranslate.popclipext   Author: wizyoung   File: pyopenssl.py    (MIT License) View Source Project 6 votes vote down vote up
def recv_into(self, *args, **kwargs):
        try:
            return self.connection.recv_into(*args, **kwargs)
        except OpenSSL.SSL.SysCallError as e:
            if self.suppress_ragged_eofs and e.args == (-1, 'Unexpected EOF'):
                return 0
            else:
                raise SocketError(str(e))
        except OpenSSL.SSL.ZeroReturnError as e:
            if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN:
                return 0
            else:
                raise
        except OpenSSL.SSL.WantReadError:
            rd = util.wait_for_read(self.socket, self.socket.gettimeout())
            if not rd:
                raise timeout('The read operation timed out')
            else:
                return self.recv_into(*args, **kwargs) 
Example 39
Project: googletranslate.popclipext   Author: wizyoung   File: connectionpool.py    (MIT License) View Source Project 6 votes vote down vote up
def _raise_timeout(self, err, url, timeout_value):
        """Is the error actually a timeout? Will raise a ReadTimeout or pass"""

        if isinstance(err, SocketTimeout):
            raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value)

        # See the above comment about EAGAIN in Python 3. In Python 2 we have
        # to specifically catch it and throw the timeout error
        if hasattr(err, 'errno') and err.errno in _blocking_errnos:
            raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value)

        # Catch possible read timeouts thrown as SSL errors. If not the
        # case, rethrow the original. We need to do this because of:
        # http://bugs.python.org/issue10272
        if 'timed out' in str(err) or 'did not complete (read)' in str(err):  # Python 2.6
            raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value) 
Example 40
Project: WPForce   Author: n00py   File: wpforce.py    (BSD 2-Clause "Simplified" License) View Source Project 6 votes vote down vote up
def TestSite(url):
    protocheck(url)
    print "Trying: " + url
    try:
        urllib2.urlopen(url, timeout=3)
    except urllib2.HTTPError, e:
        if e.code == 405:
            print url + " found!"
            print "Now the brute force will begin!  >:)"
        if e.code == 404:
            printout(str(e), YELLOW)
            print " - XMLRPC has been moved, removed, or blocked"
            sys.exit()
    except urllib2.URLError, g:
        printout("Could not identify XMLRPC.  Please verify the domain.\n", YELLOW)
        sys.exit()
    except socket.timeout as e:
        print type(e)
        printout("The socket timed out, try it again.", YELLOW)
        sys.exit() 
Example 41
Project: Projects   Author: it2school   File: securetransport.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, socket):
        self.socket = socket
        self.context = None
        self._makefile_refs = 0
        self._closed = False
        self._exception = None
        self._keychain = None
        self._keychain_dir = None
        self._client_cert_chain = None

        # We save off the previously-configured timeout and then set it to
        # zero. This is done because we use select and friends to handle the
        # timeouts, but if we leave the timeout set on the lower socket then
        # Python will "kindly" call select on that socket again for us. Avoid
        # that by forcing the timeout to zero.
        self._timeout = self.socket.gettimeout()
        self.socket.settimeout(0) 
Example 42
Project: Projects   Author: it2school   File: pyopenssl.py    (license) View Source Project 6 votes vote down vote up
def recv(self, *args, **kwargs):
        try:
            data = self.connection.recv(*args, **kwargs)
        except OpenSSL.SSL.SysCallError as e:
            if self.suppress_ragged_eofs and e.args == (-1, 'Unexpected EOF'):
                return b''
            else:
                raise SocketError(str(e))
        except OpenSSL.SSL.ZeroReturnError as e:
            if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN:
                return b''
            else:
                raise
        except OpenSSL.SSL.WantReadError:
            rd = util.wait_for_read(self.socket, self.socket.gettimeout())
            if not rd:
                raise timeout('The read operation timed out')
            else:
                return self.recv(*args, **kwargs)
        else:
            return data 
Example 43
Project: Projects   Author: it2school   File: pyopenssl.py    (license) View Source Project 6 votes vote down vote up
def recv_into(self, *args, **kwargs):
        try:
            return self.connection.recv_into(*args, **kwargs)
        except OpenSSL.SSL.SysCallError as e:
            if self.suppress_ragged_eofs and e.args == (-1, 'Unexpected EOF'):
                return 0
            else:
                raise SocketError(str(e))
        except OpenSSL.SSL.ZeroReturnError as e:
            if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN:
                return 0
            else:
                raise
        except OpenSSL.SSL.WantReadError:
            rd = util.wait_for_read(self.socket, self.socket.gettimeout())
            if not rd:
                raise timeout('The read operation timed out')
            else:
                return self.recv_into(*args, **kwargs) 
Example 44
Project: Projects   Author: it2school   File: connectionpool.py    (license) View Source Project 6 votes vote down vote up
def _raise_timeout(self, err, url, timeout_value):
        """Is the error actually a timeout? Will raise a ReadTimeout or pass"""

        if isinstance(err, SocketTimeout):
            raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value)

        # See the above comment about EAGAIN in Python 3. In Python 2 we have
        # to specifically catch it and throw the timeout error
        if hasattr(err, 'errno') and err.errno in _blocking_errnos:
            raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value)

        # Catch possible read timeouts thrown as SSL errors. If not the
        # case, rethrow the original. We need to do this because of:
        # http://bugs.python.org/issue10272
        if 'timed out' in str(err) or 'did not complete (read)' in str(err):  # Python 2.6
            raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value) 
Example 45
Project: nettools   Author: germandutchwindtunnels   File: Cisco.py    (GNU General Public License v2.0) View Source Project 6 votes vote down vote up
def connect_and_login(self):
        """ Establish a Telnet connection and perform a login """
        self.session = Telnet()
        try:
            self.session.open(self.host, self.port, self.response_timeout)
        except socket.timeout:
            return False

        if not self.login(self.username, self.password):
            return False

        try:
            self.execute_command_lowlevel("terminal length 0")
            self.execute_command_lowlevel("terminal width 0")
        except EOFError:
            return False

        return True 
Example 46
Project: pip-update-requirements   Author: alanhamlett   File: securetransport.py    (BSD 2-Clause "Simplified" License) View Source Project 6 votes vote down vote up
def __init__(self, socket):
        self.socket = socket
        self.context = None
        self._makefile_refs = 0
        self._closed = False
        self._exception = None
        self._keychain = None
        self._keychain_dir = None
        self._client_cert_chain = None

        # We save off the previously-configured timeout and then set it to
        # zero. This is done because we use select and friends to handle the
        # timeouts, but if we leave the timeout set on the lower socket then
        # Python will "kindly" call select on that socket again for us. Avoid
        # that by forcing the timeout to zero.
        self._timeout = self.socket.gettimeout()
        self.socket.settimeout(0) 
Example 47
Project: pip-update-requirements   Author: alanhamlett   File: pyopenssl.py    (BSD 2-Clause "Simplified" License) View Source Project 6 votes vote down vote up
def recv(self, *args, **kwargs):
        try:
            data = self.connection.recv(*args, **kwargs)
        except OpenSSL.SSL.SysCallError as e:
            if self.suppress_ragged_eofs and e.args == (-1, 'Unexpected EOF'):
                return b''
            else:
                raise SocketError(str(e))
        except OpenSSL.SSL.ZeroReturnError as e:
            if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN:
                return b''
            else:
                raise
        except OpenSSL.SSL.WantReadError:
            rd = util.wait_for_read(self.socket, self.socket.gettimeout())
            if not rd:
                raise timeout('The read operation timed out')
            else:
                return self.recv(*args, **kwargs)
        else:
            return data 
Example 48
Project: pip-update-requirements   Author: alanhamlett   File: pyopenssl.py    (BSD 2-Clause "Simplified" License) View Source Project 6 votes vote down vote up
def recv_into(self, *args, **kwargs):
        try:
            return self.connection.recv_into(*args, **kwargs)
        except OpenSSL.SSL.SysCallError as e:
            if self.suppress_ragged_eofs and e.args == (-1, 'Unexpected EOF'):
                return 0
            else:
                raise SocketError(str(e))
        except OpenSSL.SSL.ZeroReturnError as e:
            if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN:
                return 0
            else:
                raise
        except OpenSSL.SSL.WantReadError:
            rd = util.wait_for_read(self.socket, self.socket.gettimeout())
            if not rd:
                raise timeout('The read operation timed out')
            else:
                return self.recv_into(*args, **kwargs) 
Example 49
Project: pip-update-requirements   Author: alanhamlett   File: connectionpool.py    (BSD 2-Clause "Simplified" License) View Source Project 6 votes vote down vote up
def _raise_timeout(self, err, url, timeout_value):
        """Is the error actually a timeout? Will raise a ReadTimeout or pass"""

        if isinstance(err, SocketTimeout):
            raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value)

        # See the above comment about EAGAIN in Python 3. In Python 2 we have
        # to specifically catch it and throw the timeout error
        if hasattr(err, 'errno') and err.errno in _blocking_errnos:
            raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value)

        # Catch possible read timeouts thrown as SSL errors. If not the
        # case, rethrow the original. We need to do this because of:
        # http://bugs.python.org/issue10272
        if 'timed out' in str(err) or 'did not complete (read)' in str(err):  # Python 2.6
            raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value) 
Example 50
Project: pycos   Author: pgiri   File: netpycos.py    (license) View Source Project 5 votes vote down vote up
def locate(self, name, timeout=None):
        """Must be used with 'yield' as
        'loc = yield scheduler.locate("peer")'.

        Find and return location of peer with 'name'.
        """
        _Peer._lock.acquire()
        for peer in _Peer.peers.itervalues():
            if peer.name == name:
                loc = peer.location
                break
        else:
            loc = None
        _Peer._lock.release()
        if not loc:
            req = _NetRequest('locate_peer', kwargs={'name': name})
            req.event = Event()
            req_id = id(req)
            self._lock.acquire()
            self._pending_reqs[req_id] = req
            self._lock.release()
            _Peer.send_req_to(req, None)
            if (yield req.event.wait(timeout)) is False:
                req.reply = None
            loc = req.reply
            self._lock.acquire()
            self._pending_reqs.pop(req_id, None)
            self._lock.release()
        raise StopIteration(loc)