query
stringlengths
9
60
language
stringclasses
1 value
code
stringlengths
105
25.7k
url
stringlengths
91
217
socket recv timeout
python
def recv(self, n=4096, timeout='default'): """ Receive at most n bytes (default 4096) from the socket Aliases: read, get """ self._print_recv_header( '======== Receiving {0}B{timeout_text} ========', timeout, n) return self._recv_predicate(lambda s: min(n, len(s)), timeout)
https://github.com/rhelmot/nclib/blob/6147779766557ee4fafcbae683bdd2f74157e825/nclib/netcat.py#L640-L650
socket recv timeout
python
def timeout(self, seconds=None): """ Times out all streams after n seconds or wait forever if seconds is None """ if seconds is None: self.socketIO.wait() else: self.socketIO.wait(seconds=seconds)
https://github.com/RIPE-NCC/ripe-atlas-cousteau/blob/ffee2556aaa4df86525b88c269bb098de11678ec/ripe/atlas/cousteau/stream.py#L167-L175
socket recv timeout
python
def _receive_with_timeout(self, socket, timeout_s, use_multipart=False): """Check for socket activity and either return what's received on the socket or time out if timeout_s expires without anything on the socket. This is implemented in loops of self.try_length_ms milliseconds to allow Ctrl-C handling to take place. """ if timeout_s is config.FOREVER: timeout_ms = config.FOREVER else: timeout_ms = int(1000 * timeout_s) poller = zmq.Poller() poller.register(socket, zmq.POLLIN) ms_so_far = 0 try: for interval_ms in self.intervals_ms(timeout_ms): sockets = dict(poller.poll(interval_ms)) ms_so_far += interval_ms if socket in sockets: if use_multipart: return socket.recv_multipart() else: return socket.recv() else: raise core.SocketTimedOutError(timeout_s) except KeyboardInterrupt: raise core.SocketInterruptedError(ms_so_far / 1000.0)
https://github.com/tjguk/networkzero/blob/0e3e81d2e9200b25a83ac07741612283599486d7/networkzero/sockets.py#L204-L232
socket recv timeout
python
def settimeout(self, timeout): """set the timeout for this specific socket :param timeout: the number of seconds the socket's blocking operations should block before raising a ``socket.timeout`` :type timeout: float or None """ if timeout is not None: timeout = float(timeout) self._timeout = timeout
https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/io/sockets.py#L528-L538
socket recv timeout
python
def recv(self, timeout=None): """Receive, optionally with *timeout* in seconds. """ if timeout: timeout *= 1000. for sub in list(self.subscribers) + self._hooks: self.poller.register(sub, POLLIN) self._loop = True try: while self._loop: sleep(0) try: socks = dict(self.poller.poll(timeout=timeout)) if socks: for sub in self.subscribers: if sub in socks and socks[sub] == POLLIN: m__ = Message.decode(sub.recv_string(NOBLOCK)) if not self._filter or self._filter(m__): if self._translate: url = urlsplit(self.sub_addr[sub]) host = url[1].split(":")[0] m__.sender = (m__.sender.split("@")[0] + "@" + host) yield m__ for sub in self._hooks: if sub in socks and socks[sub] == POLLIN: m__ = Message.decode(sub.recv_string(NOBLOCK)) self._hooks_cb[sub](m__) else: # timeout yield None except ZMQError as err: LOGGER.exception("Receive failed: %s", str(err)) finally: for sub in list(self.subscribers) + self._hooks: self.poller.unregister(sub)
https://github.com/pytroll/posttroll/blob/8e811a0544b5182c4a72aed074b2ff8c4324e94d/posttroll/subscriber.py#L186-L223
socket recv timeout
python
def timeout(self, value): """Sets a custom timeout value for this session""" if value == TIMEOUT_SESSION: self._config.timeout = None self._backend_client.expires = None else: self._config.timeout = value self._calculate_expires()
https://github.com/anomaly/vishnu/blob/5b3a6a69beedc8554cc506ddfab273760d61dc65/vishnu/session.py#L235-L243
socket recv timeout
python
def recvall(self, timeout=0.5): """ Receive the RCON command response :param timeout: The timeout between consequent data receive :return str: The RCON command response with header stripped out """ response = '' self.socket.setblocking(False) start = time.time() while True: if response and time.time() - start > timeout: break elif time.time() - start > timeout * 2: break try: data = self.socket.recv(4096) if data: response += data.replace(self._rconreplystring, '') start = time.time() else: time.sleep(0.1) except socket.error: pass return response.strip()
https://github.com/anthonynguyen/pyrcon/blob/278cba95dd4d53a347d37acfce556ad375370e15/pyrcon/rcon.py#L97-L122
socket recv timeout
python
async def check_ping_timeout(self): """Make sure the client is still sending pings. This helps detect disconnections for long-polling clients. """ if self.closed: raise exceptions.SocketIsClosedError() if time.time() - self.last_ping > self.server.ping_interval + 5: self.server.logger.info('%s: Client is gone, closing socket', self.sid) # Passing abort=False here will cause close() to write a # CLOSE packet. This has the effect of updating half-open sockets # to their correct state of disconnected await self.close(wait=False, abort=False) return False return True
https://github.com/miguelgrinberg/python-engineio/blob/261fd67103cb5d9a44369415748e66fdf62de6fb/engineio/asyncio_socket.py#L50-L65
socket recv timeout
python
def timeout(self, timeout): '''Set a new :attr:`timeout` for this protocol ''' if self._timeout is None: self.event('connection_made').bind(self._add_timeout) self.event('connection_lost').bind(self._cancel_timeout) self._timeout = timeout or 0 self._add_timeout(None)
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/async/mixins.py#L116-L123
socket recv timeout
python
def recv(self): """Non-blocking network receive. Return list of (response, future) tuples """ responses = self._recv() if not responses and self.requests_timed_out(): log.warning('%s timed out after %s ms. Closing connection.', self, self.config['request_timeout_ms']) self.close(error=Errors.RequestTimedOutError( 'Request timed out after %s ms' % self.config['request_timeout_ms'])) return () # augment respones w/ correlation_id, future, and timestamp for i, (correlation_id, response) in enumerate(responses): try: with self._lock: (future, timestamp) = self.in_flight_requests.pop(correlation_id) except KeyError: self.close(Errors.KafkaConnectionError('Received unrecognized correlation id')) return () latency_ms = (time.time() - timestamp) * 1000 if self._sensors: self._sensors.request_time.record(latency_ms) log.debug('%s Response %d (%s ms): %s', self, correlation_id, latency_ms, response) responses[i] = (response, future) return responses
https://github.com/dpkp/kafka-python/blob/f6a8a38937688ea2cc5dc13d3d1039493be5c9b5/kafka/conn.py#L900-L929
socket recv timeout
python
def timer_expired(self): """ This method is invoked in context of the timer thread, so we cannot directly throw exceptions (we can, but they would be in the wrong thread), so instead we shut down the socket of the connection. When the timeout happens in early phases of the connection setup, there is no socket object on the HTTP connection yet, in that case we retry after the retry duration, indefinitely. So we do not guarantee in all cases that the overall operation times out after the specified timeout. """ if self._http_conn.sock is not None: self._shutdown = True self._http_conn.sock.shutdown(socket.SHUT_RDWR) else: # Retry after the retry duration self._timer.cancel() self._timer = threading.Timer(self._retrytime, HTTPTimeout.timer_expired, [self]) self._timer.start()
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/cim_http.py#L221-L240
socket recv timeout
python
def recv_with_timeout(self, timeout=1): """Receive a complete ISOTP message, blocking until a message is received or the specified timeout is reached. If timeout is 0, then this function doesn't block and returns the first frame in the receive buffer or None if there isn't any.""" msg = self.ins.recv(timeout) t = time.time() if msg is None: raise Scapy_Exception("Timeout") return self.basecls, msg, t
https://github.com/secdev/scapy/blob/3ffe757c184017dd46464593a8f80f85abc1e79a/scapy/contrib/isotp.py#L612-L621
socket recv timeout
python
def aiohttp_socket_timeout(socket_timeout_s): """ Return a aiohttp.ClientTimeout object with only socket timeouts set. """ return aiohttp.ClientTimeout(total=None, connect=None, sock_connect=socket_timeout_s, sock_read=socket_timeout_s)
https://github.com/desbma/sacad/blob/a7a010c4d9618a0c90927f1acb530101ca05fac4/sacad/http_helpers.py#L15-L20
socket recv timeout
python
def readable(self, timeout=2): """ Checks whether self.recv() will block or not. Optional arguments: * timeout=1 - Wait for the socket to be readable, for timeout amount of time. """ with self.lock: if len(self._buffer) > self._index: return True else: if self._select([self._socket], [], [], timeout)[0] == []: return False else: return True
https://github.com/jamieleshaw/lurklib/blob/a861f35d880140422103dd78ec3239814e85fd7e/lurklib/core.py#L166-L180
socket recv timeout
python
def timeout_callback(self): """过期回调函数. 如果设置了timeout则会启动一个协程按当前时间和最近的响应时间只差递归的执行这个回调 """ # Check if elapsed time since last response exceeds our configured # maximum keep alive timeout value now = time() time_elapsed = now - self._last_response_time if time_elapsed < self.timeout: time_left = self.timeout - time_elapsed self._timeout_handler = ( self._loop.call_later( time_left, self.timeout_callback ) ) else: logger.info('KeepAlive Timeout. Closing connection.') responseb = self.encoder({ "MPRPC": self.VERSION, "CODE": 504 }) self._stream_writer.write(responseb) self.close()
https://github.com/Basic-Components/msgpack-rpc-protocol/blob/7983ace5d5cfd7214df6803f9b1de458df5fe3b1/python/pymprpc/server/protocol.py#L234-L259
socket recv timeout
python
def timeout(self, timeout): """Set the timeout.""" self._proxy_json._timeout = timeout self._proxy_http._timeout = timeout
https://github.com/OCA/odoorpc/blob/d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0/odoorpc/rpc/__init__.py#L245-L248
socket recv timeout
python
def receive_until_end(self, timeout=None): """ Reads and blocks until the socket closes Used for the "shell" command, where STDOUT and STDERR are just redirected to the terminal with no length """ if self.receive_fixed_length(4) != "OKAY": raise SocketError("Socket communication failed: " "the server did not return a valid response") # The time at which the receive starts start_time = time.clock() output = "" while True: if timeout is not None: self.socket.settimeout(timeout - (time.clock() - start_time)) chunk = '' try: chunk = self.socket.recv(4096).decode("ascii") except socket.timeout: return output if not chunk: return output output += chunk
https://github.com/noahgoldman/adbpy/blob/ecbff8a8f151852b5c36847dc812582a8674a503/adbpy/socket.py#L102-L131
socket recv timeout
python
def _packet_timeout(self, packet, now): """ Check packet for timeout. """ if now >= packet["timeout"]: # timed out return False if now >= packet["resend"]: # resend command self._send_command(packet) return False # keep packet return True
https://github.com/TangoAlpha/liffylights/blob/7ae9ed947ecf039734014d98b6e18de0f26fa1d3/liffylights.py#L239-L251
socket recv timeout
python
def recv(self, mac_addr=broadcast_addr, timeout=0): """read packet off the recv queue for a given address, optional timeout to block and wait for packet""" # recv on the broadcast address "00:..:00" will give you all packets (for promiscuous mode) if self.keep_listening: try: return self.inq[str(mac_addr)].get(timeout=timeout) except Empty: return "" else: self.log("is down.")
https://github.com/pirate/mesh-networking/blob/e8da35d2ecded6930cf2180605bf28479ee555c7/mesh/links.py#L76-L85
socket recv timeout
python
def timeout_requesting(self): """Timeout requesting in REQUESTING state. Not specifiyed in [:rfc:`7844`] [:rfc:`2131#section-3.1`]:: might retransmit the DHCPREQUEST message four times, for a total delay of 60 seconds """ logger.debug("C3.2: T. In %s, timeout receiving response to request, ", self.current_state) if self.discover_requests >= MAX_ATTEMPTS_REQUEST: logger.debug('C2.3: T. Maximum number %s of REQUESTs ' 'reached, already sent %s, raise ERROR.', MAX_ATTEMPTS_REQUEST, self.disover_requests) raise self.ERROR() logger.debug("C2.3: F. Maximum number of REQUESTs retries not reached," "raise REQUESTING.") raise self.REQUESTING()
https://github.com/juga0/dhcpcanon/blob/9f51a29e57fe93dc93fb22bb0ed12fcfe9557e59/dhcpcanon/dhcpcapfsm.py#L464-L484
socket recv timeout
python
def settimeout(self, timeout): ''' Set the timeout value for this socket. ''' if timeout is None: self._block = True elif float(timeout) == 0.0: self._block = False else: self._timeout = float(timeout) self._block = True
https://github.com/jsommers/switchyard/blob/fdcb3869c937dcedbd6ea7a7822ebd412bf1e2b0/switchyard/lib/socket/socketemu.py#L487-L497
socket recv timeout
python
def listen(self, timeout=10): """ Listen for incoming messages. Timeout is used to check if the server must be switched off. :param timeout: Socket Timeout in seconds """ self._socket.settimeout(float(timeout)) while not self.stopped.isSet(): try: data, client_address = self._socket.recvfrom(4096) except socket.timeout: continue try: self.receive_datagram((data, client_address)) except RuntimeError: logger.exception("Exception with Executor") self._socket.close()
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/reverse_proxy/coap.py#L226-L243
socket recv timeout
python
def listen(self, timeout=10): """ Listen for incoming messages. Timeout is used to check if the server must be switched off. :param timeout: Socket Timeout in seconds """ self._socket.settimeout(float(timeout)) while not self.stopped.isSet(): try: data, client_address = self._socket.recvfrom(4096) except socket.timeout: continue try: #Start a new thread not to block other requests args = ((data, client_address), ) t = threading.Thread(target=self.receive_datagram, args=args) t.daemon = True t.start() except RuntimeError: logging.exception("Exception with Executor") logging.debug("closing socket") self._socket.close()
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/forward_proxy/coap.py#L130-L151
socket recv timeout
python
def timeout(seconds, err_msg="xtls: function run too long."): """ 超时检测 :param seconds: 函数最长运行时间 :param err_msg: 超时提示 """ def decorator(function): def _on_timeout(signum, frame): raise TimeoutError(err_msg) @wraps(function) def wrapper(*args, **kwargs): signal.signal(signal.SIGALRM, _on_timeout) signal.alarm(seconds) try: result = function(*args, **kwargs) finally: signal.alarm(0) return result return wrapper return decorator
https://github.com/xlzd/xtls/blob/b3cc0ab24197ecaa39adcad7cd828cada9c04a4e/xtls/codehelper.py#L101-L124
socket recv timeout
python
def listen(self, timeout=10): """ Listen for incoming messages. Timeout is used to check if the server must be switched off. :param timeout: Socket Timeout in seconds """ self._socket.settimeout(float(timeout)) while not self.stopped.isSet(): try: data, client_address = self._socket.recvfrom(4096) if len(client_address) > 2: client_address = (client_address[0], client_address[1]) except socket.timeout: continue except Exception as e: if self._cb_ignore_listen_exception is not None and isinstance(self._cb_ignore_listen_exception, collections.Callable): if self._cb_ignore_listen_exception(e, self): continue raise try: serializer = Serializer() message = serializer.deserialize(data, client_address) if isinstance(message, int): logger.error("receive_datagram - BAD REQUEST") rst = Message() rst.destination = client_address rst.type = defines.Types["RST"] rst.code = message rst.mid = self._messageLayer.fetch_mid() self.send_datagram(rst) continue logger.debug("receive_datagram - " + str(message)) if isinstance(message, Request): transaction = self._messageLayer.receive_request(message) if transaction.request.duplicated and transaction.completed: logger.debug("message duplicated, transaction completed") if transaction.response is not None: self.send_datagram(transaction.response) continue elif transaction.request.duplicated and not transaction.completed: logger.debug("message duplicated, transaction NOT completed") self._send_ack(transaction) continue args = (transaction, ) t = threading.Thread(target=self.receive_request, args=args) t.start() # self.receive_datagram(data, client_address) elif isinstance(message, Response): logger.error("Received response from %s", message.source) else: # is Message transaction = self._messageLayer.receive_empty(message) if transaction is not None: with transaction: self._blockLayer.receive_empty(message, transaction) self._observeLayer.receive_empty(message, transaction) except RuntimeError: logger.exception("Exception with Executor") self._socket.close()
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/server/coap.py#L124-L185
socket recv timeout
python
def wait_socket(host, port, timeout=120): ''' Wait for socket opened on remote side. Return False after timeout ''' return wait_result(lambda: check_socket(host, port), True, timeout)
https://github.com/tipsi/tipsi_tools/blob/1aba960c9890ceef2fb5e215b98b1646056ee58e/tipsi_tools/unix.py#L132-L136
socket recv timeout
python
def _disable_socket_timeout(self, socket): """ Depending on the combination of python version and whether we're connecting over http or https, we might need to access _sock, which may or may not exist; or we may need to just settimeout on socket itself, which also may or may not have settimeout on it. To avoid missing the correct one, we try both. We also do not want to set the timeout if it is already disabled, as you run the risk of changing a socket that was non-blocking to blocking, for example when using gevent. """ sockets = [socket, getattr(socket, '_sock', None)] for s in sockets: if not hasattr(s, 'settimeout'): continue timeout = -1 if hasattr(s, 'gettimeout'): timeout = s.gettimeout() # Don't change the timeout if it is already disabled. if timeout is None or timeout == 0.0: continue s.settimeout(None)
https://github.com/docker/docker-py/blob/613d6aad83acc9931ff2ecfd6a6c7bd8061dc125/docker/api/client.py#L417-L443
socket recv timeout
python
def retry_timeout(api, retries=3): """Retry API call when a timeout occurs.""" @wraps(api) def retry_api(*args, **kwargs): """Retrying API.""" for i in range(1, retries + 1): try: return api(*args, **kwargs) except RequestTimeout: if i == retries: raise return retry_api
https://github.com/ggravlingen/pytradfri/blob/63750fa8fb27158c013d24865cdaa7fb82b3ab53/pytradfri/api/libcoap_api.py#L198-L210
socket recv timeout
python
def receive(self): """Receive TCP response, looping to get whole thing or timeout.""" try: buffer = self._socket.recv(BUFFER_SIZE) except socket.timeout as error: # Something is wrong, assume it's offline temporarily _LOGGER.error("Error receiving: %s", error) # self._socket.close() return "" # Read until a newline or timeout buffering = True response = '' while buffering: if '\n' in buffer.decode("utf8"): response = buffer.decode("utf8").split('\n')[0] buffering = False else: try: more = self._socket.recv(BUFFER_SIZE) except socket.timeout: more = None if not more: buffering = False response = buffer.decode("utf8") else: buffer += more return response
https://github.com/lindsaymarkward/python-yeelight-sunflower/blob/4ec72d005ce307f832429620ba0bcbf6b236eead/yeelightsunflower/main.py#L77-L104
socket recv timeout
python
def _SetSocketTimeouts(self): """Sets the timeouts for socket send and receive.""" # Note that timeout must be an integer value. If timeout is a float # it appears that zmq will not enforce the timeout. timeout = int(self.timeout_seconds * 1000) receive_timeout = min( self._ZMQ_SOCKET_RECEIVE_TIMEOUT_MILLISECONDS, timeout) send_timeout = min(self._ZMQ_SOCKET_SEND_TIMEOUT_MILLISECONDS, timeout) self._zmq_socket.setsockopt(zmq.RCVTIMEO, receive_timeout) self._zmq_socket.setsockopt(zmq.SNDTIMEO, send_timeout)
https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/engine/zeromq_queue.py#L161-L171
socket recv timeout
python
def _timeout_expired(self): """ A timeout was supplied during setup, and the time has run out. """ self._did_timeout = True try: self.transport.signalProcess('TERM') except error.ProcessExitedAlready: # XXX why don't we just always do this? self.transport.loseConnection() fail = Failure(RuntimeError("timeout while launching Tor")) self._maybe_notify_connected(fail)
https://github.com/meejah/txtorcon/blob/14053b95adf0b4bd9dd9c317bece912a26578a93/txtorcon/controller.py#L1291-L1303
socket recv timeout
python
def run(self, timeout = 0): """ Run a proactor loop and return new socket events. Timeout is a timedelta object, 0 if active coros or None. kqueue timeout param is a integer number of nanoseconds (seconds/10**9). """ ptimeout = int( timeout.days*86400000000000 + timeout.microseconds*1000 + timeout.seconds*1000000000 if timeout else (self.n_resolution if timeout is None else 0) ) if ptimeout>sys.maxint: ptimeout = sys.maxint if self.tokens: events = self.kq.kevent(None, self.default_size, ptimeout) # should check here if timeout isn't negative or larger than maxint len_events = len(events)-1 for nr, ev in enumerate(events): fd = ev.ident act = ev.udata if ev.flags & EV_ERROR: ev = EV_SET(fd, act.flags, EV_DELETE) self.kq.kevent(ev) self.handle_error_event(act, 'System error %s.'%ev.data) else: if nr == len_events: ret = self.yield_event(act) if not ret: ev.flags = EV_ADD | EV_ENABLE | EV_ONESHOT self.kq.kevent(ev) return ret else: if not self.handle_event(act): ev.flags = EV_ADD | EV_ENABLE | EV_ONESHOT self.kq.kevent(ev) else: sleep(timeout)
https://github.com/ionelmc/python-cogen/blob/83b0edb88425eba6e5bfda9f1dcd34642517e2a8/cogen/core/proactors/kqueue_impl.py#L37-L76
socket recv timeout
python
def recv(self, timeout=None): """Receive an ISOTP frame, blocking if none is available in the buffer for at most 'timeout' seconds.""" try: return self.rx_queue.get(timeout is None or timeout > 0, timeout) except queue.Empty: return None
https://github.com/secdev/scapy/blob/3ffe757c184017dd46464593a8f80f85abc1e79a/scapy/contrib/isotp.py#L1287-L1294
socket recv timeout
python
def poll(self, event, timeout=None): """Wait for a socket event. Posssible *event* values are the strings "recv", "send" and "acks". Whent the timeout is present and not :const:`None`, it should be a floating point number specifying the timeout for the operation in seconds (or fractions thereof). For "recv" or "send" the :meth:`poll` method returns :const:`True` if a next :meth:`recv` or :meth:`send` operation would be non-blocking. The "acks" event may only be used with a data-link-connection type socket; the call then returns :const:`True` if the counter of received acknowledgements was greater than zero and decrements the counter by one. """ return self.llc.poll(self._tco, event, timeout)
https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/llcp/socket.py#L142-L156
socket recv timeout
python
def _set_socket_timeout(cls, sock, timeout=None): """Temporarily set a socket timeout in order to respect a timeout provided to .iter_chunks().""" if timeout is not None: prev_timeout = sock.gettimeout() try: if timeout is not None: sock.settimeout(timeout) yield except socket.timeout: raise cls.ProcessStreamTimeout("socket read timed out with timeout {}".format(timeout)) finally: if timeout is not None: sock.settimeout(prev_timeout)
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/java/nailgun_protocol.py#L225-L237
socket recv timeout
python
def recv_until(self, s, max_size=None, timeout='default'): """ Recieve data from the socket until the given substring is observed. Data in the same datagram as the substring, following the substring, will not be returned and will be cached for future receives. Aliases: read_until, readuntil, recvuntil """ self._print_recv_header( '======== Receiving until {0}{timeout_text} ========', timeout, repr(s)) if max_size is None: max_size = 2 ** 62 def _predicate(buf): try: return min(buf.index(s) + len(s), max_size) except ValueError: return 0 if len(buf) < max_size else max_size return self._recv_predicate(_predicate, timeout)
https://github.com/rhelmot/nclib/blob/6147779766557ee4fafcbae683bdd2f74157e825/nclib/netcat.py#L652-L672
socket recv timeout
python
def wait_for(self, event, *, check=None, timeout=None): """|coro| Waits for a WebSocket event to be dispatched. This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way. The ``timeout`` parameter is passed onto :func:`asyncio.wait_for`. By default, it does not timeout. Note that this does propagate the :exc:`asyncio.TimeoutError` for you in case of timeout and is provided for ease of use. In case the event returns multiple arguments, a :class:`tuple` containing those arguments is returned instead. Please check the :ref:`documentation <discord-api-events>` for a list of events and their parameters. This function returns the **first event that meets the requirements**. Examples --------- Waiting for a user reply: :: @client.event async def on_message(message): if message.content.startswith('$greet'): channel = message.channel await channel.send('Say hello!') def check(m): return m.content == 'hello' and m.channel == channel msg = await client.wait_for('message', check=check) await channel.send('Hello {.author}!'.format(msg)) Waiting for a thumbs up reaction from the message author: :: @client.event async def on_message(message): if message.content.startswith('$thumb'): channel = message.channel await channel.send('Send me that \N{THUMBS UP SIGN} reaction, mate') def check(reaction, user): return user == message.author and str(reaction.emoji) == '\N{THUMBS UP SIGN}' try: reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check) except asyncio.TimeoutError: await channel.send('\N{THUMBS DOWN SIGN}') else: await channel.send('\N{THUMBS UP SIGN}') Parameters ------------ event: :class:`str` The event name, similar to the :ref:`event reference <discord-api-events>`, but without the ``on_`` prefix, to wait for. check: Optional[predicate] A predicate to check what to wait for. The arguments must meet the parameters of the event being waited for. timeout: Optional[:class:`float`] The number of seconds to wait before timing out and raising :exc:`asyncio.TimeoutError`. Raises ------- asyncio.TimeoutError If a timeout is provided and it was reached. Returns -------- Any Returns no arguments, a single argument, or a :class:`tuple` of multiple arguments that mirrors the parameters passed in the :ref:`event reference <discord-api-events>`. """ future = self.loop.create_future() if check is None: def _check(*args): return True check = _check ev = event.lower() try: listeners = self._listeners[ev] except KeyError: listeners = [] self._listeners[ev] = listeners listeners.append((future, check)) return asyncio.wait_for(future, timeout, loop=self.loop)
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/client.py#L640-L736
socket recv timeout
python
def _timeout_cb(self, method): """Call the timeout handler due. """ self._anything_done = True logger.debug("_timeout_cb() called for: {0!r}".format(method)) result = method() # pylint: disable=W0212 rec = method._pyxmpp_recurring if rec: self._prepare_pending() return True if rec is None and result is not None: logger.debug(" auto-recurring, restarting in {0} s" .format(result)) tag = glib.timeout_add(int(result * 1000), self._timeout_cb, method) self._timer_sources[method] = tag else: self._timer_sources.pop(method, None) self._prepare_pending() return False
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/glib.py#L226-L246
socket recv timeout
python
def recv(self, timeout=-1): """ Receive and item from our Sender. This will block unless our Sender is ready, either forever or unless *timeout* milliseconds. """ if self.ready: return self.other.handover(self) return self.pause(timeout=timeout)
https://github.com/cablehead/vanilla/blob/c9f5b86f45720a30e8840fb68b1429b919c4ca66/vanilla/message.py#L312-L320
socket recv timeout
python
def timeout(self, value): """Sets the timeout associated with the serial port.""" self.check_pyb() try: self.pyb.serial.timeout = value except: # timeout is a property so it calls code, and that can fail # if the serial port is closed. pass
https://github.com/dhylands/rshell/blob/a92a8fa8074ac792241c83c640a51b394667c324/rshell/main.py#L1611-L1619
socket recv timeout
python
def request(self, method, url, **kwargs): """ Overrides ``requests.Session.request`` to set the timeout. """ resp = super(ClientSession, self).request( method, url, timeout=self._timeout, **kwargs) return resp
https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/_client_session.py#L61-L68
socket recv timeout
python
def make_socket(): '''Creates a socket suitable for SSDP searches. The socket will have a default timeout of 0.2 seconds (this works well for the :py:func:search function which interleaves sending requests and reading responses. ''' mreq = struct.pack("4sl", socket.inet_aton(MCAST_IP), socket.INADDR_ANY) sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind(('', MCAST_PORT)) sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) sock.settimeout(0.2) return sock
https://github.com/the-allanc/greyupnp/blob/7d40c4c306f3e87a453494c9ad3c1ac1626d02c5/greyupnp/ssdp.py#L21-L34
socket recv timeout
python
def _relay(self, **kwargs): """Send the request through the server and return the HTTP response.""" retval = None delay_time = 2 # For connection retries read_attempts = 0 # For reading from socket while retval is None: # Evict can return False sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock_fp = sock.makefile('rwb') # Used for pickle try: sock.connect((self.host, self.port)) cPickle.dump(kwargs, sock_fp, cPickle.HIGHEST_PROTOCOL) sock_fp.flush() retval = cPickle.load(sock_fp) except: # pylint: disable=W0702 exc_type, exc, _ = sys.exc_info() socket_error = exc_type is socket.error if socket_error and exc.errno == 111: # Connection refused sys.stderr.write('Cannot connect to multiprocess server. I' 's it running? Retrying in {0} seconds.\n' .format(delay_time)) time.sleep(delay_time) delay_time = min(64, delay_time * 2) elif exc_type is EOFError or socket_error and exc.errno == 104: # Failure during socket READ if read_attempts >= 3: raise ClientException('Successive failures reading ' 'from the multiprocess server.') sys.stderr.write('Lost connection with multiprocess server' ' during read. Trying again.\n') read_attempts += 1 else: raise finally: sock_fp.close() sock.close() if isinstance(retval, Exception): raise retval # pylint: disable=E0702 return retval
https://github.com/michael-lazar/rtv/blob/ccef2af042566ad384977028cf0bde01bc524dda/rtv/packages/praw/handlers.py#L198-L235
socket recv timeout
python
def recv(self, timeout=None): """ High-level IRC buffering system and processor. Optional arguments: * timeout=None - Time to wait before returning None. Defaults to waiting forever. """ with self.lock: if timeout != None: if self.readable(timeout) == False: return None data = self._raw_recv() segments = data.split() if segments[1] == 'JOIN': who = self._from_(segments[0][1:]) channel = segments[2][1:] if channel not in self.channels: self.stepback(append=False) return 'JOIN', self.join_(channel, process_only=True) else: self.channels[channel]['USERS'][who[0]] = \ ['', '', '', '', ''] return 'JOIN', (who, channel) elif segments[1] == 'PART': who = self._from_(segments[0].replace(':', '', 1)) channel = segments[2] del self.channels[channel]['USERS'][who[0]] try: reason = ' '.join(segments[3:]).replace(':', '', 1) return 'PART', (who, channel, reason) except IndexError: who = self._from_(segments[0].replace(':', '', 1)) return 'PART', (who, channel, '') elif segments[1] == 'PRIVMSG': who = self._from_(segments[0].replace(':', '', 1)) msg = ' '.join(segments[3:]).replace(':', '', 1) rvalue = 'PRIVMSG', (who, segments[2], msg) if msg.find('\001') == 0: rctcp = self.ctcp_decode(msg) return 'CTCP', (rvalue[1][0], rvalue[1][1], rctcp) else: return rvalue elif segments[1] == 'NOTICE': who = self._from_(segments[0].replace(':', '', 1)) msg = ' '.join(segments[3:]).replace(':', '', 1) if msg.find('\001') == 0: msg = self.ctcp_decode(msg) return 'CTCP_REPLY', (who, segments[2], msg) return 'NOTICE', (who, segments[2], msg) elif segments[1] == 'MODE': mode = ' '.join(segments[3:]).replace(':', '', 1) who = self._from_(segments[0][1:]) target = segments[2] if target != self.current_nick: self.parse_cmode_string(mode, target) return 'MODE', (who, segments[2], mode) else: return 'MODE', (who, mode.replace(':', '', 1)) elif segments[1] == 'KICK': who = self._from_(segments[0].replace(':', '', 1)) if self.current_nick == segments[3]: del self.channels[segments[2]] else: del self.channels[segments[2]]['USERS'][segments[3]] reason = ' '.join(segments[4:]).replace(':', '', 1) return 'KICK', (who, segments[2], segments[3], reason) elif segments[1] == 'INVITE': who = self._from_(segments[0].replace(':', '', 1)) channel = segments[3].replace(':', '', 1) return 'INVITE', (who, segments[2], channel) elif segments[1] == 'NICK': who = self._from_(segments[0].replace(':', '', 1)) new_nick = ' '.join(segments[2:]).replace(':', '', 1) if self.current_nick == who[0]: self.current_nick = new_nick for channel in self.channels: if who[0] in self.channels[channel]['USERS']: priv_level = self.channels[channel]['USERS'][who[0]] del self.channels[channel]['USERS'][who[0]] self.channels[channel]['USERS'][new_nick] = priv_level return 'NICK', (who, new_nick) elif segments[1] == 'TOPIC': who = self._from_(segments[0].replace(':', '', 1)) channel = segments[2] topic = ' '.join(segments[3:]).replace(':', '', 1) self.channels[channel]['TOPIC'] = topic return 'TOPIC', (who, channel, topic) elif segments[1] == 'QUIT': who = self._from_(segments[0].replace(':', '', 1)) msg = ' '.join(segments[2:]).replace(':', '', 1) for channel in self.channels: if who[0] in self.channels[channel]['USERS']: del self.channels[channel]['USERS'][who[0]] return 'QUIT', (who, msg) elif segments[1] == '250': self.lusers['HIGHESTCONNECTIONS'] = segments[6] self.lusers['TOTALCONNECTIONS'] = segments[9][1:] return 'LUSERS', self.lusers elif segments[1] == '251': self.lusers['USERS'] = segments[5] self.lusers['INVISIBLE'] = segments[8] self.lusers['SERVERS'] = segments[11] return 'LUSERS', self.lusers elif segments[1] == '252': self.lusers['OPERATORS'] = segments[3] return 'LUSERS', self.lusers elif segments[1] == '253': self.lusers['UNKNOWN'] = segments[3] return 'LUSERS', self.lusers elif segments[1] == '254': self.lusers['CHANNELS'] = segments[3] return 'LUSERS', self.lusers elif segments[1] == '255': self.lusers['CLIENTS'] = segments[5] self.lusers['LSERVERS'] = segments[8] return 'LUSERS', self.lusers elif segments[1] == '265': self.lusers['LOCALUSERS'] = segments[6] self.lusers['LOCALMAX'] = segments[8] return 'LUSERS', self.lusers elif segments[1] == '266': self.lusers['GLOBALUSERS'] = segments[6] self.lusers['GLOBALMAX'] = segments[8] return 'LUSERS', self.lusers elif segments[0] == 'ERROR': self.quit() return 'ERROR', ' '.join(segments[1:]).replace(':', '', 1) else: self.stepback(append=False) return 'UNKNOWN', self._recv(rm_first=False)
https://github.com/jamieleshaw/lurklib/blob/a861f35d880140422103dd78ec3239814e85fd7e/lurklib/core.py#L286-L435
socket recv timeout
python
def timeout_keep_alive_handler(self): """ Called on a keep-alive connection if no new data is received after a short delay. """ if not self.transport.is_closing(): event = h11.ConnectionClosed() self.conn.send(event) self.transport.close()
https://github.com/encode/uvicorn/blob/b4c138910bb63475efd028627e10adda722e4937/uvicorn/protocols/http/h11_impl.py#L320-L327
socket recv timeout
python
def receive_one_ping(mySocket, myID, timeout): """ Receive the ping from the socket. Timeout = in ms """ timeLeft = timeout/1000 while True: # Loop while waiting for packet or timeout startedSelect = default_timer() whatReady = select.select([mySocket], [], [], timeLeft) howLongInSelect = (default_timer() - startedSelect) if whatReady[0] == []: # Timeout return None, 0, 0, 0, 0 timeReceived = default_timer() recPacket, addr = mySocket.recvfrom(ICMP_MAX_RECV) ipHeader = recPacket[:20] iphVersion, iphTypeOfSvc, iphLength, \ iphID, iphFlags, iphTTL, iphProtocol, \ iphChecksum, iphSrcIP, iphDestIP = struct.unpack( "!BBHHHBBHII", ipHeader ) icmpHeader = recPacket[20:28] icmpType, icmpCode, icmpChecksum, \ icmpPacketID, icmpSeqNumber = struct.unpack( "!BBHHH", icmpHeader ) if icmpPacketID == myID: # Our packet dataSize = len(recPacket) - 28 #print (len(recPacket.encode())) return timeReceived, (dataSize+8), iphSrcIP, icmpSeqNumber, iphTTL timeLeft = timeLeft - howLongInSelect if timeLeft <= 0: return None, 0, 0, 0, 0
https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/DemoPrograms/ping.py#L390-L427
socket recv timeout
python
def request(self, message, timeout=False, *args, **kwargs): """Populate connection pool, send message, return BytesIO, and cleanup""" if not self.connection_pool.full(): self.connection_pool.put(self._register_socket()) _socket = self.connection_pool.get() # setting timeout to None enables the socket to block. if timeout or timeout is None: _socket.settimeout(timeout) data = self.send_and_receive(_socket, message, *args, **kwargs) if self.connection.proto in Socket.streams: _socket.shutdown(socket.SHUT_RDWR) return Response(data, None, None)
https://github.com/hugapi/hug/blob/080901c81576657f82e2432fd4a82f1d0d2f370c/hug/use.py#L251-L267
socket recv timeout
python
async def _delay(self): """Check for a 'retry-after' header to set timeout, otherwise use configured timeout. """ if self._response is None: await asyncio.sleep(0) if self._response.headers.get('retry-after'): await asyncio.sleep(int(self._response.headers['retry-after'])) else: await asyncio.sleep(self._timeout)
https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/polling/async_arm_polling.py#L83-L92
socket recv timeout
python
def wait_socket(_socket, session, timeout=1): """Helper function for testing non-blocking mode. This function blocks the calling thread for <timeout> seconds - to be used only for testing purposes. Also available at `ssh2.utils.wait_socket` """ directions = session.block_directions() if directions == 0: return 0 readfds = [_socket] \ if (directions & LIBSSH2_SESSION_BLOCK_INBOUND) else () writefds = [_socket] \ if (directions & LIBSSH2_SESSION_BLOCK_OUTBOUND) else () return select(readfds, writefds, (), timeout)
https://github.com/ParallelSSH/ssh2-python/blob/a3d077ec6370a870a463ddb3dbafc9bf0f5dc11a/examples/nonblocking_execute.py#L36-L51
socket recv timeout
python
def timeout_request_renewing(self): """Timeout of renewing on RENEWING state. Same comments as in :func:`dhcpcapfsm.DHCPCAPFSM.timeout_requesting`. """ logger.debug("C5.2:T In %s, timeout receiving response to request.", self.current_state) if self.request_attempts >= MAX_ATTEMPTS_REQUEST: logger.debug('C2.3: T Maximum number %s of REQUESTs ' 'reached, already sent %s, wait to rebinding time.', MAX_ATTEMPTS_REQUEST, self.disover_requests) # raise self.ERROR() logger.debug("C2.3: F. Maximum number of REQUESTs retries not reached," "raise RENEWING.") raise self.RENEWING()
https://github.com/juga0/dhcpcanon/blob/9f51a29e57fe93dc93fb22bb0ed12fcfe9557e59/dhcpcanon/dhcpcapfsm.py#L487-L503
socket recv timeout
python
def catch_timeout(f): """ A decorator to handle read timeouts from Twitter. """ def new_f(self, *args, **kwargs): try: return f(self, *args, **kwargs) except (requests.exceptions.ReadTimeout, requests.packages.urllib3.exceptions.ReadTimeoutError) as e: log.warning("caught read timeout: %s", e) self.connect() return f(self, *args, **kwargs) return new_f
https://github.com/DocNow/twarc/blob/47dd87d0c00592a4d583412c9d660ba574fc6f26/twarc/decorators.py#L81-L93
socket recv timeout
python
def set_default_timeout(timeout=None, connect_timeout=None, read_timeout=None): """ The purpose of this function is to install default socket timeouts and retry policy for requests calls. Any requests issued through the requests wrappers defined in this module will have these automatically set, unless explicitly overriden. The default timeouts and retries set through this option apply to the entire process. For that reason, it is recommended that this function is only called once during startup, and from the main thread, before any other threads are spawned. :param timeout timeout for socket connections and reads in seconds. This is a convenience argument that applies the same default to both connection and read timeouts. :param connect_timeout timeout for socket connections in seconds. :param read_timeout timeout for socket reads in seconds. """ global DEFAULT_CONNECT_TIMEOUT global DEFAULT_READ_TIMEOUT DEFAULT_CONNECT_TIMEOUT = connect_timeout if connect_timeout is not None \ else timeout DEFAULT_READ_TIMEOUT = read_timeout if read_timeout is not None \ else timeout
https://github.com/rackerlabs/fleece/blob/42d79dfa0777e99dbb09bc46105449a9be5dbaa9/fleece/requests.py#L13-L36
socket recv timeout
python
def timeout(duration): """ A decorator to force a time limit on the execution of an external function. :param int duration: the timeout duration :raises: TypeError, if duration is anything other than integer :raises: ValueError, if duration is a negative integer :raises TimeoutError, if the external function execution crosses 'duration' time """ if not isinstance(duration, int): raise TypeError("timeout duration should be a positive integer") if duration <= 0: raise ValueError("timeoutDuration should be a positive integer") def decorator(func): def wrapped_func(*args, **kwargs): try: def alarm_handler(signum, stack): raise TimeoutError() signal.signal(signal.SIGALRM, alarm_handler) signal.alarm(duration) reply = func(*args, **kwargs) except TimeoutError as e: raise e return reply return wrapped_func return decorator
https://github.com/anayjoshi/cronus/blob/52544e63913f37d7fca570168b878737f16fe39c/cronus/timeout.py#L23-L53
socket recv timeout
python
def set_tx_timeout(self, channel, timeout): """ Sets the transmission timeout. :param int channel: CAN channel, to be used (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`). :param float timeout: Transmit timeout in seconds (value 0 disables this feature). """ UcanSetTxTimeout(self._handle, channel, int(timeout * 1000))
https://github.com/hardbyte/python-can/blob/cdc5254d96072df7739263623f3e920628a7d214/can/interfaces/systec/ucan.py#L576-L583
socket recv timeout
python
def receive(self, timeout=None): """Receive data through websocket""" log.debug('Receiving') if not self._socket: log.warn('No connection') return try: if timeout: rv = self._socket.poll(timeout) if not rv: log.info('Connection timeouted') return 'Quit' data = self._socket.recv_bytes() except Exception: log.error('Connection lost') return 'Quit' log.debug('Got %s' % data) return data.decode('utf-8')
https://github.com/Kozea/wdb/blob/6af7901b02e866d76f8b0a697a8c078e5b70d1aa/client/wdb/__init__.py#L758-L776
socket recv timeout
python
def recv(self): """Receive message from the backend or wait unilt next message.""" try: message = self.ws.recv() return json.loads(message) except websocket._exceptions.WebSocketConnectionClosedException as ex: raise SelenolWebSocketClosedException() from ex
https://github.com/selenol/selenol-python/blob/53775fdfc95161f4aca350305cb3459e6f2f808d/selenol_python/connections.py#L47-L53
socket recv timeout
python
def run(self, timeout = 0): """ Run a proactor loop and return new socket events. Timeout is a timedelta object, 0 if active coros or None. kqueue timeout param is a integer number of nanoseconds (seconds/10**9). """ ptimeout = float( timeout.microseconds/1000000+timeout.seconds if timeout else (self.resolution if timeout is None else 0) ) if self.tokens: events = self.kcontrol(None, self.default_size, ptimeout) len_events = len(events)-1 for nr, ev in enumerate(events): fd = ev.ident act = self.shadow.pop(fd) if ev.flags & KQ_EV_ERROR: self.kcontrol((kevent(fd, act.flags, KQ_EV_DELETE),), 0) self.handle_error_event(act, 'System error %s.'%ev.data) else: if nr == len_events: ret = self.yield_event(act) if not ret: ev.flags = KQ_EV_ADD | KQ_EV_ONESHOT self.kcontrol((ev,), 0) self.shadow[fd] = act return ret else: if not self.handle_event(act): ev.flags = KQ_EV_ADD | KQ_EV_ONESHOT self.kcontrol((ev,), 0) self.shadow[fd] = act else: sleep(timeout)
https://github.com/ionelmc/python-cogen/blob/83b0edb88425eba6e5bfda9f1dcd34642517e2a8/cogen/core/proactors/stdlib_kqueue_impl.py#L48-L83
socket recv timeout
python
def makeSocket(self, timeout=1): """Override SocketHandler.makeSocket, to allow creating wrapped TLS sockets""" plain_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if hasattr(plain_socket, 'settimeout'): plain_socket.settimeout(timeout) wrapped_socket = ssl.wrap_socket( plain_socket, ca_certs=self.ca_certs, cert_reqs=self.reqs, keyfile=self.keyfile, certfile=self.certfile ) wrapped_socket.connect((self.host, self.port)) return wrapped_socket
https://github.com/severb/graypy/blob/32018c41a792e71a8de9f9e14f770d1bc60c2313/graypy/handler.py#L451-L468
socket recv timeout
python
def time_out(self): """If we don't get a response within time the RTSP request time out. This usually happens if device isn't available on specified IP. """ _LOGGER.warning('Response timed out %s', self.session.host) self.stop() self.callback(SIGNAL_FAILED)
https://github.com/Kane610/axis/blob/b2b44ce595c7b722b5e13eabcab7b91f048e1808/axis/rtsp.py#L112-L119
socket recv timeout
python
def keep_alive_timeout_callback(self): """ Check if elapsed time since last response exceeds our configured maximum keep alive timeout value and if so, close the transport pipe and let the response writer handle the error. :return: None """ time_elapsed = time() - self._last_response_time if time_elapsed < self.keep_alive_timeout: time_left = self.keep_alive_timeout - time_elapsed self._keep_alive_timeout_handler = self.loop.call_later( time_left, self.keep_alive_timeout_callback ) else: logger.debug("KeepAlive Timeout. Closing connection.") self.transport.close() self.transport = None
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/server.py#L230-L247
socket recv timeout
python
async def loop(self): """Pulse every timeout seconds until stopped.""" while not self.stopped: self.timeout_handle = self.pyvlx.connection.loop.call_later( self.timeout_in_seconds, self.loop_timeout) await self.loop_event.wait() if not self.stopped: self.loop_event.clear() await self.pulse() self.cancel_loop_timeout() self.stopped_event.set()
https://github.com/Julius2342/pyvlx/blob/ee78e1324bcb1be5b8d1a9d05ab5496b72eae848/pyvlx/heartbeat.py#L37-L47
socket recv timeout
python
def cycle(self): """Here we wait for a response from the server after sending it something, and dispatch appropriate action to that response.""" try: (buffer, (raddress, rport)) = self.sock.recvfrom(MAX_BLKSIZE) except socket.timeout: log.warning("Timeout waiting for traffic, retrying...") raise TftpTimeout("Timed-out waiting for traffic") # Ok, we've received a packet. Log it. log.debug("Received %d bytes from %s:%s", len(buffer), raddress, rport) # And update our last updated time. self.last_update = time.time() # Decode it. recvpkt = self.factory.parse(buffer) # Check for known "connection". if raddress != self.address: log.warning("Received traffic from %s, expected host %s. Discarding" % (raddress, self.host)) if self.tidport and self.tidport != rport: log.warning("Received traffic from %s:%s but we're " "connected to %s:%s. Discarding." % (raddress, rport, self.host, self.tidport)) # If there is a packethook defined, call it. We unconditionally # pass all packets, it's up to the client to screen out different # kinds of packets. This way, the client is privy to things like # negotiated options. if self.packethook: self.packethook(recvpkt) # And handle it, possibly changing state. self.state = self.state.handle(recvpkt, raddress, rport) # If we didn't throw any exceptions here, reset the retry_count to # zero. self.retry_count = 0
https://github.com/msoulier/tftpy/blob/af2f2fe89a3bf45748b78703820efb0986a8207a/tftpy/TftpContexts.py#L165-L205
socket recv timeout
python
def _validate_timeout(seconds: float): """Creates an int from 60000 to 4294967294 that represents a valid millisecond wireless LAN timeout""" val = int(seconds * 1000) assert 60000 <= val <= 4294967294, "Bad value: {}".format(val) return val
https://github.com/TadLeonard/tfatool/blob/12da2807b5fb538c5317ef255d846b32ceb174d0/tfatool/config.py#L48-L53
socket recv timeout
python
def recv_all(self, timeout='default'): """ Return all data recieved until connection closes. Aliases: read_all, readall, recvall """ self._print_recv_header('======== Receiving until close{timeout_text} ========', timeout) return self._recv_predicate(lambda s: 0, timeout, raise_eof=False)
https://github.com/rhelmot/nclib/blob/6147779766557ee4fafcbae683bdd2f74157e825/nclib/netcat.py#L674-L683
socket recv timeout
python
def wait_for_service(host, port, timeout=DEFAULT_TIMEOUT): """ Return True if connection to the host and port is successful within the timeout. @param host: str: hostname of the server @param port: int: TCP port to which to connect @param timeout: int: length of time in seconds to try to connect before giving up @return: bool """ service = ServiceURL('tcp://{}:{}'.format(host, port), timeout) return service.wait()
https://github.com/pmac/urlwait/blob/0a846177a15a7f6f5a9d76c7229e572f779a048a/urlwait.py#L108-L118
socket recv timeout
python
def get_timeout(service): """ Returns either a custom timeout for the given service, or a default """ custom_timeout_key = "RESTCLIENTS_%s_TIMEOUT" % service.upper() if hasattr(settings, custom_timeout_key): return getattr(settings, custom_timeout_key) default_key = "RESTCLIENTS_DEFAULT_TIMEOUT" if hasattr(settings, default_key): return getattr(settings, default_key) return OLD_DEFAULT_TIMEOUT
https://github.com/uw-it-aca/uw-restclients/blob/e12dcd32bf5296b6ebdf71798031594afb7852cb/restclients/dao_implementation/__init__.py#L6-L17
socket recv timeout
python
def timelimit(timeout): """borrowed from web.py""" def _1(function): def _2(*args, **kw): class Dispatch(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.result = None self.error = None self.setDaemon(True) self.start() def run(self): try: self.result = function(*args, **kw) except: self.error = sys.exc_info() c = Dispatch() c.join(timeout) if c.isAlive(): raise TimeoutError, 'took too long' if c.error: raise c.error[0], c.error[1] return c.result return _2 return _1
https://github.com/dfm/ugly/blob/bc09834849184552619ee926d7563ed37630accb/ugly/feedfinder.py#L53-L80
socket recv timeout
python
def _read_all_from_socket(self, timeout): """ Read all packets we currently can on the socket. Returns list of tuples. Each tuple contains a packet and the time at which it was received. NOTE: The receive time is the time when our recv() call returned, which greatly depends on when it was called. The time is NOT the time at which the packet arrived at our host, but it's the closest we can come to the real ping time. If nothing was received within the timeout time, the return list is empty. First read is blocking with timeout, so we'll wait at least that long. Then, in case any more packets have arrived, we read everything we can from the socket in non-blocking mode. """ pkts = [] try: self._sock.settimeout(timeout) while True: p = self._sock.recv(64) # Store the packet and the current time pkts.append((bytearray(p), time.time())) # Continue the loop to receive any additional packets that # may have arrived at this point. Changing the socket to # non-blocking (by setting the timeout to 0), so that we'll # only continue the loop until all current packets have been # read. self._sock.settimeout(0) except socket.timeout: # In the first blocking read with timout, we may not receive # anything. This is not an error, it just means no data was # available in the specified time. pass except socket.error as e: # When we read in non-blocking mode, we may get this error with # errno 11 to indicate that no more data is available. That's ok, # just like the timeout. if e.errno == errno.EWOULDBLOCK: pass else: # We're not expecting any other socket exceptions, so we # re-raise in that case. raise if self._ipv6_address_present: try: self._sock6.settimeout(timeout) while True: p = self._sock6.recv(128) pkts.append((bytearray(p), time.time())) self._sock6.settimeout(0) except socket.timeout: pass except socket.error as e: if e.errno == errno.EWOULDBLOCK: pass else: raise return pkts
https://github.com/romana/multi-ping/blob/59f024c867a17fae5b4a7b52f97effc6fb1b0ca5/multiping/__init__.py#L305-L367
socket recv timeout
python
def receives(self, *args, **kwargs): """Pop the next `Request` and assert it matches. Returns None if the server is stopped. Pass a `Request` or request pattern to specify what client request to expect. See the tutorial for examples. Pass ``timeout`` as a keyword argument to override this server's ``request_timeout``. """ timeout = kwargs.pop('timeout', self._request_timeout) end = time.time() + timeout matcher = Matcher(*args, **kwargs) while not self._stopped: try: # Short timeout so we notice if the server is stopped. request = self._request_q.get(timeout=0.05) except Empty: if time.time() > end: raise AssertionError('expected to receive %r, got nothing' % matcher.prototype) else: if matcher.matches(request): return request else: raise AssertionError('expected to receive %r, got %r' % (matcher.prototype, request))
https://github.com/ajdavis/mongo-mockup-db/blob/ff8a3f793def59e9037397ef60607fbda6949dac/mockupdb/__init__.py#L1310-L1335
socket recv timeout
python
def wait(self): "wait for a message, respecting timeout" data=self.getcon().recv(256) # this can raise socket.timeout if not data: raise PubsubDisco if self.reset: self.reset=False # i.e. ack it. reset is used to tell the wait-thread there was a reconnect (though it's plausible that this never happens) raise PubsubDisco self.buf+=data msg,self.buf=complete_message(self.buf) return msg
https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/redismodel.py#L117-L126
socket recv timeout
python
def _timeout(self, watcher, events): """Connector timed out, raise a timeout error.""" self.timedout = True self._finish() self.deferred.errback(TimeoutError())
https://github.com/bfrog/whizzer/blob/a1e43084b3ac8c1f3fb4ada081777cdbf791fd77/whizzer/client.py#L121-L125
socket recv timeout
python
async def _perform_ping_timeout(self, delay: int): """ Handle timeout gracefully. Args: delay (int): delay before raising the timeout (in seconds) """ # pause for delay seconds await sleep(delay) # then continue error = TimeoutError( 'Ping timeout: no data received from server in {timeout} seconds.'.format( timeout=self.PING_TIMEOUT)) await self.on_data_error(error)
https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/client.py#L162-L175
socket recv timeout
python
def _reset_timeout(self): """Reset timeout for date keep alive.""" if self._timeout: self._timeout.cancel() self._timeout = self.loop.call_later(self.client.timeout, self.transport.close)
https://github.com/jameshilliard/hlk-sw16/blob/4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56/hlk_sw16/protocol.py#L30-L35
socket recv timeout
python
def request(self, method, *, path=None, json=None, params=None, headers=None, timeout=None, backoff_cap=None, **kwargs): """Performs an HTTP request with the given parameters. Implements exponential backoff. If `ConnectionError` occurs, a timestamp equal to now + the default delay (`BACKOFF_DELAY`) is assigned to the object. The timestamp is in UTC. Next time the function is called, it either waits till the timestamp is passed or raises `TimeoutError`. If `ConnectionError` occurs two or more times in a row, the retry count is incremented and the new timestamp is calculated as now + the default delay multiplied by two to the power of the number of retries. If a request is successful, the backoff timestamp is removed, the retry count is back to zero. Args: method (str): HTTP method (e.g.: ``'GET'``). path (str): API endpoint path (e.g.: ``'/transactions'``). json (dict): JSON data to send along with the request. params (dict): Dictionary of URL (query) parameters. headers (dict): Optional headers to pass to the request. timeout (int): Optional timeout in seconds. backoff_cap (int): The maximal allowed backoff delay in seconds to be assigned to a node. kwargs: Optional keyword arguments. """ backoff_timedelta = self.get_backoff_timedelta() if timeout is not None and timeout < backoff_timedelta: raise TimeoutError if backoff_timedelta > 0: time.sleep(backoff_timedelta) connExc = None timeout = timeout if timeout is None else timeout - backoff_timedelta try: response = self._request( method=method, timeout=timeout, url=self.node_url + path if path else self.node_url, json=json, params=params, headers=headers, **kwargs, ) except ConnectionError as err: connExc = err raise err finally: self.update_backoff_time(success=connExc is None, backoff_cap=backoff_cap) return response
https://github.com/bigchaindb/bigchaindb-driver/blob/c294a535f0696bd19483ae11a4882b74e6fc061e/bigchaindb_driver/connection.py#L41-L99
socket recv timeout
python
def responses_from_socket(sock, timeout=10): '''Yield SSDP search responses and advertisements from the provided socket. Args: sock: A socket suitable for use to send a broadcast message - preferably one created by :py:func:`make_socket`. timeout (int / float): Overall time in seconds for how long to wait for before no longer listening for responses. Yields: dict of string -> string: Case-insensitive dictionary of header name to header value pairs extracted from the response. ''' now = time.time() give_up_by = now + timeout while now < give_up_by: try: data = sock.recv(1024) except socket.timeout: now = time.time() continue # We handle either search responses or announcements. for data_prefix in [ b'HTTP/1.1 200 OK', b'NOTIFY * HTTP/1.1', ]: if data[:len(data_prefix)] == data_prefix: break else: now = time.time() continue yield decode_response(data) now = time.time() continue
https://github.com/the-allanc/greyupnp/blob/7d40c4c306f3e87a453494c9ad3c1ac1626d02c5/greyupnp/ssdp.py#L90-L127
socket recv timeout
python
def requestTimedOut(self, reply): """Trap the timeout. In Async mode requestTimedOut is called after replyFinished""" # adapt http_call_result basing on receiving qgs timer timout signal self.exception_class = RequestsExceptionTimeout self.http_call_result.exception = RequestsExceptionTimeout("Timeout error")
https://github.com/boundlessgeo/lib-qgis-commons/blob/d25d13803db08c18632b55d12036e332f006d9ac/qgiscommons2/network/networkaccessmanager.py#L268-L272
socket recv timeout
python
def timeout(self): """Handle fetcher timeout and call apriopriate handler. Is called by the cache object and should _not_ be called by fetcher or application. Do nothing when the fetcher is not active any more (after one of handlers was already called).""" if not self.active: return if not self._try_backup_item(): if self._timeout_handler: self._timeout_handler(self.address) else: self._error_handler(self.address, None) self.cache.invalidate_object(self.address) self._deactivate()
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/cache.py#L270-L286
socket recv timeout
python
def retry_with_delay(f, delay=60): """ Retry the wrapped requests.request function in case of ConnectionError. Optionally limit the number of retries or set the delay between retries. """ @wraps(f) def inner(*args, **kwargs): kwargs['timeout'] = 5 remaining = get_retries() + 1 while remaining: remaining -= 1 try: return f(*args, **kwargs) except (requests.ConnectionError, requests.Timeout): if not remaining: raise gevent.sleep(delay) return inner
https://github.com/iancmcc/ouimeaux/blob/89f3d05e7ae0a356690f898a4e1801ea3c104200/ouimeaux/utils.py#L68-L85
socket recv timeout
python
def _recv_internal(self, timeout): """ Read a message from the serial device. :param timeout: .. warning:: This parameter will be ignored. The timeout value of the channel is used. :returns: Received message and False (because not filtering as taken place). .. warning:: Flags like is_extended_id, is_remote_frame and is_error_frame will not be set over this function, the flags in the return message are the default values. :rtype: can.Message, bool """ try: # ser.read can return an empty string # or raise a SerialException rx_byte = self.ser.read() except serial.SerialException: return None, False if rx_byte and ord(rx_byte) == 0xAA: s = bytearray(self.ser.read(4)) timestamp = (struct.unpack('<I', s))[0] dlc = ord(self.ser.read()) s = bytearray(self.ser.read(4)) arb_id = (struct.unpack('<I', s))[0] data = self.ser.read(dlc) rxd_byte = ord(self.ser.read()) if rxd_byte == 0xBB: # received message data okay msg = Message(timestamp=timestamp/1000, arbitration_id=arb_id, dlc=dlc, data=data) return msg, False else: return None, False
https://github.com/hardbyte/python-can/blob/cdc5254d96072df7739263623f3e920628a7d214/can/interfaces/serial/serial_can.py#L109-L156
socket recv timeout
python
def await_socket(self, timeout): """Wait up to a given timeout for a process to write socket info.""" return self.await_metadata_by_name(self._name, 'socket', timeout, self._socket_type)
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/pantsd/process_manager.py#L333-L335
socket recv timeout
python
def calculate_timeout(http_date): """Extract request timeout from e.g. ``Retry-After`` header. Notes: Per :rfc:`2616#section-14.37`, the ``Retry-After`` header can be either an integer number of seconds or an HTTP date. This function can handle either. Arguments: http_date (:py:class:`str`): The date to parse. Returns: :py:class:`int`: The timeout, in seconds. """ try: return int(http_date) except ValueError: date_after = parse(http_date) utc_now = datetime.now(tz=timezone.utc) return int((date_after - utc_now).total_seconds())
https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/core.py#L65-L85
socket recv timeout
python
def wait(timeout=300): """Wait util target connected""" if env(): cij.err("cij.ssh.wait: Invalid SSH environment") return 1 timeout_backup = cij.ENV.get("SSH_CMD_TIMEOUT") try: time_start = time.time() cij.ENV["SSH_CMD_TIMEOUT"] = "3" while True: time_current = time.time() if (time_current - time_start) > timeout: cij.err("cij.ssh.wait: Timeout") return 1 status, _, _ = command(["exit"], shell=True, echo=False) if not status: break cij.info("cij.ssh.wait: Time elapsed: %d seconds" % (time_current - time_start)) finally: if timeout_backup is None: del cij.ENV["SSH_CMD_TIMEOUT"] else: cij.ENV["SSH_CMD_TIMEOUT"] = timeout_backup return 0
https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/modules/cij/ssh.py#L143-L175
socket recv timeout
python
def wait_for_url(url, timeout=DEFAULT_TIMEOUT): """ Return True if connection to the host and port specified in url is successful within the timeout. @param url: str: connection url for a TCP service @param timeout: int: length of time in seconds to try to connect before giving up @raise RuntimeError: if no port is given or can't be guessed via the scheme @return: bool """ service = ServiceURL(url, timeout) return service.wait()
https://github.com/pmac/urlwait/blob/0a846177a15a7f6f5a9d76c7229e572f779a048a/urlwait.py#L121-L132
socket recv timeout
python
def client_pause(self, timeout): """ Suspend all the Redis clients for the specified amount of time :param timeout: milliseconds to pause clients """ if not isinstance(timeout, (int, long)): raise DataError("CLIENT PAUSE timeout must be an integer") return self.execute_command('CLIENT PAUSE', str(timeout))
https://github.com/andymccurdy/redis-py/blob/cdfe2befbe00db4a3c48c9ddd6d64dea15f6f0db/redis/client.py#L893-L900
socket recv timeout
python
def recv(self, timeout=None): """Overwrite standard recv for timeout calls to catch interrupt errors. """ if timeout: try: testsock = self._zmq.select([self.socket], [], [], timeout)[0] except zmq.ZMQError as e: if e.errno == errno.EINTR: testsock = None else: raise if not testsock: return rv = self.socket.recv(self._zmq.NOBLOCK) return LogRecord.from_dict(json.loads(rv)) else: return super(ZeroMQPullSubscriber, self).recv(timeout)
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/log/logbook_zmqpush.py#L98-L114
socket recv timeout
python
def serve_forever(self, poll_interval=0.5): """ Wait for incomming requests. """ self.serial_port.timeout = poll_interval while not self._shutdown_request: try: self.serve_once() except (CRCError, struct.error) as e: log.error('Can\'t handle request: {0}'.format(e)) except (SerialTimeoutException, ValueError): pass
https://github.com/AdvancedClimateSystems/uModbus/blob/0560a42308003f4072d988f28042b8d55b694ad4/umodbus/server/serial/__init__.py#L62-L72
socket recv timeout
python
def run(self, timeout = 0): """ Run a proactor loop and return new socket events. Timeout is a timedelta object, 0 if active coros or None. epoll timeout param is a integer number of miliseconds (seconds/1000). """ ptimeout = int(timeout.microseconds/1000+timeout.seconds*1000 if timeout else (self.m_resolution if timeout is None else 0)) if self.tokens: epoll_fd = self.epoll_fd events = epoll_wait(epoll_fd, 1024, ptimeout) len_events = len(events)-1 for nr, (ev, fd) in enumerate(events): act = self.shadow.pop(fd) if ev & EPOLLHUP: epoll_ctl(self.epoll_fd, EPOLL_CTL_DEL, fd, 0) self.handle_error_event(act, 'Hang up.', ConnectionClosed) elif ev & EPOLLERR: epoll_ctl(self.epoll_fd, EPOLL_CTL_DEL, fd, 0) self.handle_error_event(act, 'Unknown error.') else: if nr == len_events: ret = self.yield_event(act) if not ret: epoll_ctl(epoll_fd, EPOLL_CTL_MOD, fd, ev | EPOLLONESHOT) self.shadow[fd] = act return ret else: if not self.handle_event(act): epoll_ctl(epoll_fd, EPOLL_CTL_MOD, fd, ev | EPOLLONESHOT) self.shadow[fd] = act else: sleep(timeout)
https://github.com/ionelmc/python-cogen/blob/83b0edb88425eba6e5bfda9f1dcd34642517e2a8/cogen/core/proactors/epoll_impl.py#L49-L83
socket recv timeout
python
def socket_recv(self): """ Called by TelnetServer when recv data is ready. """ try: data = self.sock.recv(2048) except socket.error, ex: print ("?? socket.recv() error '%d:%s' from %s" % (ex[0], ex[1], self.addrport())) raise BogConnectionLost() ## Did they close the connection? size = len(data) if size == 0: raise BogConnectionLost() ## Update some trackers self.last_input_time = time.time() self.bytes_received += size ## Test for telnet commands for byte in data: self._iac_sniffer(byte) ## Look for newline characters to get whole lines from the buffer while True: mark = self.recv_buffer.find('\n') if mark == -1: break cmd = self.recv_buffer[:mark].strip() self.command_list.append(cmd) self.cmd_ready = True self.recv_buffer = self.recv_buffer[mark+1:]
https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/third_party/miniboa-r42/miniboa/telnet.py#L288-L320
socket recv timeout
python
def _RetryRequest(self, timeout=None, **request_args): """Retry the request a few times before we determine it failed. Sometimes the frontend becomes loaded and issues a 500 error to throttle the clients. We wait Client.error_poll_min seconds between each attempt to back off the frontend. Note that this does not affect any timing algorithm in the client itself which is controlled by the Timer() class. Args: timeout: Timeout for retry. **request_args: Args to the requests.request call. Returns: a tuple of duration, urllib.request.urlopen response. """ while True: try: now = time.time() if not timeout: timeout = config.CONFIG["Client.http_timeout"] result = requests.request(**request_args) # By default requests doesn't raise on HTTP error codes. result.raise_for_status() # Requests does not always raise an exception when an incorrect response # is received. This fixes that behaviour. if not result.ok: raise requests.RequestException(response=result) return time.time() - now, result # Catch any exceptions that dont have a code (e.g. socket.error). except IOError as e: self.consecutive_connection_errors += 1 # Request failed. If we connected successfully before we attempt a few # connections before we determine that it really failed. This might # happen if the front end is loaded and returns a few throttling 500 # messages. if self.active_base_url is not None: # Propagate 406 immediately without retrying, as 406 is a valid # response that indicates a need for enrollment. response = getattr(e, "response", None) if getattr(response, "status_code", None) == 406: raise if self.consecutive_connection_errors >= self.retry_error_limit: # We tried several times but this really did not work, just fail it. logging.info( "Too many connection errors to %s, retrying another URL", self.active_base_url) self.active_base_url = None raise e # Back off hard to allow the front end to recover. logging.debug( "Unable to connect to frontend. Backing off %s seconds.", self.error_poll_min) self.Wait(self.error_poll_min) # We never previously connected, maybe the URL/proxy is wrong? Just fail # right away to allow callers to try a different URL. else: raise e
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/client/grr_response_client/comms.py#L366-L429
socket recv timeout
python
def timeout_request_rebinding(self): """Timeout of request rebinding on REBINDING state. Same comments as in :func:`dhcpcapfsm.DHCPCAPFSM.timeout_requesting`. """ logger.debug("C6.2:T In %s, timeout receiving response to request.", self.current_state) if self.request_attempts >= MAX_ATTEMPTS_REQUEST: logger.debug('C.2.3: T. Maximum number %s of REQUESTs ' 'reached, already sent %s, wait lease time expires.', MAX_ATTEMPTS_REQUEST, self.disover_requests) # raise self.ERROR() logger.debug("C2.3: F. Maximum number of REQUESTs retries not reached," "raise REBINDING.") raise self.REBINDING()
https://github.com/juga0/dhcpcanon/blob/9f51a29e57fe93dc93fb22bb0ed12fcfe9557e59/dhcpcanon/dhcpcapfsm.py#L506-L522
socket recv timeout
python
def read_packet(sock, timeout=None): """ Read data from socket *sock* Returns None if something went wrong """ sock.settimeout(timeout) dlen, data = None, None try: if os.name == 'nt': # Windows implementation datalen = sock.recv(SZ) dlen, = struct.unpack("l", datalen) data = b'' while len(data) < dlen: data += sock.recv(dlen) else: # Linux/MacOSX implementation # Thanks to eborisch: # See issue 1106 datalen = temp_fail_retry(socket.error, sock.recv, SZ, socket.MSG_WAITALL) if len(datalen) == SZ: dlen, = struct.unpack("l", datalen) data = temp_fail_retry(socket.error, sock.recv, dlen, socket.MSG_WAITALL) except socket.timeout: raise except socket.error: data = None finally: sock.settimeout(None) if data is not None: try: return pickle.loads(data) except Exception: # Catch all exceptions to avoid locking spyder if DEBUG_EDITOR: traceback.print_exc(file=STDERR) return
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/bsdsocket.py#L54-L92
socket recv timeout
python
def timeout(seconds): """ Raises a TimeoutError if a function does not terminate within specified seconds. """ def _timeout_error(signal, frame): raise TimeoutError("Operation did not finish within \ {} seconds".format(seconds)) def timeout_decorator(func): @wraps(func) def timeout_wrapper(*args, **kwargs): signal.signal(signal.SIGALRM, _timeout_error) signal.alarm(seconds) try: return func(*args, **kwargs) finally: signal.alarm(0) return timeout_wrapper return timeout_decorator
https://github.com/romaryd/python-awesome-decorators/blob/8c83784149338ab69a25797e1097b214d33a5958/awesomedecorators/timez.py#L36-L58
socket recv timeout
python
def _recv(self): """Take all available bytes from socket, return list of any responses from parser""" recvd = [] self._lock.acquire() if not self._can_send_recv(): log.warning('%s cannot recv: socket not connected', self) self._lock.release() return () while len(recvd) < self.config['sock_chunk_buffer_count']: try: data = self._sock.recv(self.config['sock_chunk_bytes']) # We expect socket.recv to raise an exception if there are no # bytes available to read from the socket in non-blocking mode. # but if the socket is disconnected, we will get empty data # without an exception raised if not data: log.error('%s: socket disconnected', self) self._lock.release() self.close(error=Errors.KafkaConnectionError('socket disconnected')) return [] else: recvd.append(data) except SSLWantReadError: break except ConnectionError as e: if six.PY2 and e.errno == errno.EWOULDBLOCK: break log.exception('%s: Error receiving network data' ' closing socket', self) self._lock.release() self.close(error=Errors.KafkaConnectionError(e)) return [] except BlockingIOError: if six.PY3: break self._lock.release() raise recvd_data = b''.join(recvd) if self._sensors: self._sensors.bytes_received.record(len(recvd_data)) try: responses = self._protocol.receive_bytes(recvd_data) except Errors.KafkaProtocolError as e: self._lock.release() self.close(e) return [] else: self._lock.release() return responses
https://github.com/dpkp/kafka-python/blob/f6a8a38937688ea2cc5dc13d3d1039493be5c9b5/kafka/conn.py#L931-L983
socket recv timeout
python
def settimeout(self, timeout): """ Set the timeout to the websocket. timeout: timeout time(second). """ self.sock_opt.timeout = timeout if self.sock: self.sock.settimeout(timeout)
https://github.com/websocket-client/websocket-client/blob/3c25814664fef5b78716ed8841123ed1c0d17824/websocket/_core.py#L138-L146
socket recv timeout
python
def _handle_timeout(self) -> None: """Called by IOLoop when the requested timeout has passed.""" self._timeout = None while True: try: ret, num_handles = self._multi.socket_action(pycurl.SOCKET_TIMEOUT, 0) except pycurl.error as e: ret = e.args[0] if ret != pycurl.E_CALL_MULTI_PERFORM: break self._finish_pending_requests() # In theory, we shouldn't have to do this because curl will # call _set_timeout whenever the timeout changes. However, # sometimes after _handle_timeout we will need to reschedule # immediately even though nothing has changed from curl's # perspective. This is because when socket_action is # called with SOCKET_TIMEOUT, libcurl decides internally which # timeouts need to be processed by using a monotonic clock # (where available) while tornado uses python's time.time() # to decide when timeouts have occurred. When those clocks # disagree on elapsed time (as they will whenever there is an # NTP adjustment), tornado might call _handle_timeout before # libcurl is ready. After each timeout, resync the scheduled # timeout with libcurl's current state. new_timeout = self._multi.timeout() if new_timeout >= 0: self._set_timeout(new_timeout)
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/curl_httpclient.py#L159-L186
socket recv timeout
python
def timeout(seconds=10, default_output='default_output'): """ function wrapper that limits the amount of time it has to run optional args: seconds - how long it has until the function times out default_output - what will be returned instead of an error """ def decorator(func): def _handle_timeout(signum, frame): """ throw the custom TimeoutError if called """ raise TimeoutError(strerror(ETIME)) def wrapper(*args, **kwargs): """ main wrapper for the error """ # set up the propper error signal signal(SIGALRM, _handle_timeout) # set the time the function has to run alarm(seconds) try: result = func(*args, **kwargs) except TimeoutError: if default_output == 'default_output': raise else: result = default_output finally: # cancel the timer alarm(0) return result return wraps(func)(wrapper) return decorator
https://github.com/CodyKochmann/time_limit/blob/447a640d3e187bb4775d780b757c6d9bdc88ae34/time_limit/__init__.py#L38-L68
socket recv timeout
python
def _timeout(seconds): """Context manager that runs code block until timeout is reached. Example usage:: try: with _timeout(10): do_stuff() except Timeout: print("do_stuff timed out") """ def _handle_timeout(*args): raise Timeout(seconds) signal.signal(signal.SIGALRM, _handle_timeout) signal.alarm(seconds) try: yield finally: signal.alarm(0) signal.signal(signal.SIGALRM, signal.SIG_DFL)
https://github.com/cs50/check50/blob/42c1f0c36baa6a24f69742d74551a9ea7a5ceb33/check50/runner.py#L52-L73
socket recv timeout
python
def socketio(request): """ Socket.IO handler - maintains the lifecycle of a Socket.IO request, sending the each of the events. Also handles adding/removing request/socket pairs to the CLIENTS dict which is used for sending on_finish events when the server stops. """ context = {} socket = SocketIOChannelProxy(request.environ["socketio"]) client_start(request, socket, context) try: if socket.on_connect(): events.on_connect.send(request, socket, context) while True: messages = socket.recv() if not messages and not socket.connected(): events.on_disconnect.send(request, socket, context) break # Subscribe and unsubscribe messages are in two parts, the # name of either and the channel, so we use an iterator that # lets us jump a step in iteration to grab the channel name # for these. messages = iter(messages) for message in messages: if message == "__subscribe__": message = messages.next() message_type = "subscribe" socket.subscribe(message) events.on_subscribe.send(request, socket, context, message) elif message == "__unsubscribe__": message = messages.next() message_type = "unsubscribe" socket.unsubscribe(message) events.on_unsubscribe.send(request, socket, context, message) else: # Socket.IO sends arrays as individual messages, so # they're put into an object in socketio_scripts.html # and given the __array__ key so that they can be # handled consistently in the on_message event. message_type = "message" if message == "__array__": message = messages.next() events.on_message.send(request, socket, context, message) log_message = format_log(request, message_type, message) if log_message: socket.handler.server.log.write(log_message) except Exception, exception: from traceback import print_exc print_exc() events.on_error.send(request, socket, context, exception) client_end(request, socket, context) return HttpResponse("")
https://github.com/stephenmcd/django-socketio/blob/b704f912551829a3bcf15872ba0e1baf81dea106/django_socketio/views.py#L10-L62
socket recv timeout
python
def a2s_ping(server_addr, timeout=2): """Ping a server .. warning:: This method for pinging is considered deprecated and may not work on certian servers. Use :func:`.a2s_info` instead. :param server_addr: (ip, port) for the server :type server_addr: tuple :param timeout: (optional) timeout in seconds :type timeout: float :raises: :class:`RuntimeError`, :class:`socket.timeout` :returns: ping response in milliseconds or `None` for timeout :rtype: :class:`float` """ ss = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) ss.connect(server_addr) ss.settimeout(timeout) ss.send(_pack('<lc', -1, b'i')) start = _time() try: data = _handle_a2s_response(ss) finally: ss.close() ping = max(0.0, _time() - start) * 1000 if data[4:5] == b'j': return ping
https://github.com/ValvePython/steam/blob/2de1364c47598410b572114e6129eab8fff71d5b/steam/game_servers.py#L574-L604
socket recv timeout
python
def _set_timeouts(self, timeouts): """ Set socket timeouts for send and receive respectively """ (send_timeout, recv_timeout) = (None, None) try: (send_timeout, recv_timeout) = timeouts except TypeError: raise EndpointError( '`timeouts` must be a pair of numbers (2, 3) which represent ' 'the timeout values for send and receive respectively') if send_timeout is not None: self.socket.set_int_option( nanomsg.SOL_SOCKET, nanomsg.SNDTIMEO, send_timeout) if recv_timeout is not None: self.socket.set_int_option( nanomsg.SOL_SOCKET, nanomsg.RCVTIMEO, recv_timeout)
https://github.com/walkr/nanoservice/blob/e2098986b1baa5f283167ae487d14f3c6c21961a/nanoservice/core.py#L79-L97