我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用errno.EWOULDBLOCK。
def _socketpair(): if hasattr(socket, 'socketpair'): return socket.socketpair() srv_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) srv_sock.bind(('127.0.0.1', 0)) srv_sock.listen(1) write_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: write_sock.setblocking(False) try: write_sock.connect(srv_sock.getsockname()[:2]) except socket.error as e: if e.args[0] in (EINPROGRESS, EWOULDBLOCK): pass else: raise write_sock.setblocking(True) read_sock = srv_sock.accept()[0] except: write_sock.close() raise finally: srv_sock.close() return (read_sock, write_sock)
def line_gen(basedir,chan): subdir = chan+".chat" sdpath = os.path.join(basedir,subdir) fn = max(x for x in os.listdir(sdpath) if x.endswith(".txt")) path = os.path.join(sdpath,fn) ch = chan.encode('utf-8') for x in tail_f(path): if x == EWOULDBLOCK: continue s = x.encode('utf-8') time,name,rest = split_line(s) if name[-1] == ':'.encode('utf-8'): t = colored(time,'cyan',attrs=['bold']) c = colored(ch,'cyan',attrs=['bold']) n = colored(name,'red',attrs=['bold']) r = highlight(rest) else: t = colored(time,'cyan') c = colored(ch,'cyan') n = colored(name,'yellow',attrs=['dark']) r = colored(rest,attrs=['dark']) yield ' '.join((t,c,n,r))
def write_to_server_socket(self, data, addr): uncomplete = False retry = 0 try: self._server_socket.sendto(data, addr) data = None while self._data_to_write_to_server_socket: data_buf = self._data_to_write_to_server_socket[0] retry = data_buf[1] + 1 del self._data_to_write_to_server_socket[0] data, addr = data_buf[0] self._server_socket.sendto(data, addr) except (OSError, IOError) as e: error_no = eventloop.errno_from_exception(e) uncomplete = True if error_no in (errno.EWOULDBLOCK,): pass else: shell.print_exception(e) return False #if uncomplete and data is not None and retry < 3: # self._data_to_write_to_server_socket.append([(data, addr), retry]) #'''
def _socketpair_compat(): """TCP/IP socketpair including Windows support""" listensock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP) listensock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) listensock.bind(("127.0.0.1", 0)) listensock.listen(1) iface, port = listensock.getsockname() sock1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP) sock1.setblocking(0) try: sock1.connect(("localhost", port)) except socket.error as err: if err.errno != errno.EINPROGRESS and err.errno != errno.EWOULDBLOCK and err.errno != EAGAIN: raise sock2, address = listensock.accept() sock2.setblocking(0) listensock.close() return (sock1, sock2)
def doRead(self): """Calls self.protocol.dataReceived with all available data. This reads up to self.bufferSize bytes of data from its socket, then calls self.dataReceived(data) to process it. If the connection is not lost through an error in the physical recv(), this function will return the result of the dataReceived call. """ try: data = self.socket.recv(self.bufferSize) except socket.error, se: if se.args[0] == EWOULDBLOCK: return else: return main.CONNECTION_LOST if not data: return main.CONNECTION_DONE return self.protocol.dataReceived(data)
def writeSomeData(self, data): """Connection.writeSomeData(data) -> #of bytes written | CONNECTION_LOST This writes as much data as possible to the socket and returns either the number of bytes read (which is positive) or a connection error code (which is negative) """ try: # Limit length of buffer to try to send, because some OSes are too # stupid to do so themselves (ahem windows) return self.socket.send(buffer(data, 0, self.SEND_LIMIT)) except socket.error, se: if se.args[0] == EINTR: return self.writeSomeData(data) elif se.args[0] in (EWOULDBLOCK, ENOBUFS): return 0 else: return main.CONNECTION_LOST
def doRead(self): """Called when my socket is ready for reading.""" read = 0 while read < self.maxThroughput: try: data, addr = self.socket.recvfrom(self.maxPacketSize) read += len(data) self.protocol.datagramReceived(data) except socket.error, se: no = se.args[0] if no in (EAGAIN, EINTR, EWOULDBLOCK): return if (no == ECONNREFUSED) or (platformType == "win32" and no == WSAECONNRESET): self.protocol.connectionRefused() else: raise except: log.deferr()
def _on_local_read(self): # handle all local read events and dispatch them to methods for # each stage self._update_activity() if not self._local_sock: return data = None try: data = self._local_sock.recv(BUF_SIZE) except (OSError, IOError) as e: if eventloop.errno_from_exception(e) in \ (errno.ETIMEDOUT, errno.EAGAIN, errno.EWOULDBLOCK): return if not data: self.destroy() return if not data: return self._server.server_transfer_ul += len(data) #TODO ============================================================ if self._stage == STAGE_STREAM: self._write_to_sock(data, self._remote_sock) return
def _send_buffer(self, buff, target, send_all=False): size = len(buff) tosend = size already_sent = 0 while tosend > 0: try: # i should be able to send a bytearray sent = target.send(buff[already_sent:]) if sent == 0: raise RuntimeError('socket connection broken') already_sent += sent tosend -= sent except socket.error as e: # if full buffers then wait for them to drain and try again if e.errno in [errno.EAGAIN, errno.EWOULDBLOCK]: if send_all: continue return buff[already_sent:] else: raise exception.SocketException(str(e)) return None
def send (self, data): try: numsent = self.socket.send (data) if numsent: self.set_event_time () return numsent except socket.error as why: if why.errno == EWOULDBLOCK: return 0 elif why.errno in asyncore._DISCONNECTED: #print (">>>>>>>>>> why.errno == asyncore.ENOTCONN", why.errno == asyncore.ENOTCONN) if os.name == "nt" and why.errno == asyncore.ENOTCONN: # winsock sometimes raise ENOTCONN and sometimes recovered. # Found this error at http://file.hungryboarder.com:8080/HBAdManager/pa.html?siteId=hboarder&zoneId=S-2 if self._raised_ENOTCONN <= 3: self._raised_ENOTCONN += 1 return 0 else: self._raised_ENOTCONN = 0 self.handle_close (700, "Connection closed unexpectedly in send") return 0 else: raise
def send(self, message, flags): with self.send_token: if not self.state.ESTABLISHED: self.err("send() in socket state {0}".format(self.state)) if self.state.CLOSE_WAIT: raise err.Error(errno.EPIPE) raise err.Error(errno.ENOTCONN) if len(message) > self.send_miu: raise err.Error(errno.EMSGSIZE) while self.send_window_slots == 0 and self.state.ESTABLISHED: if flags & nfc.llcp.MSG_DONTWAIT: raise err.Error(errno.EWOULDBLOCK) self.log("waiting on busy send window") self.send_token.wait() self.log("send {0} byte on {1}".format(len(message), str(self))) if self.state.ESTABLISHED: send_pdu = pdu.Information(self.peer, self.addr, data=message) send_pdu.ns = self.send_cnt self.send_cnt = (self.send_cnt + 1) % 16 super(DataLinkConnection, self).send(send_pdu, flags) return self.state.ESTABLISHED is True
def _socketpair_compat(): """TCP/IP socketpair including Windows support""" listensock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP) listensock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) listensock.bind(("127.0.0.1", 0)) listensock.listen(1) iface, port = listensock.getsockname() sock1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP) sock1.setblocking(0) try: sock1.connect(("127.0.0.1", port)) except socket.error as err: if err.errno != errno.EINPROGRESS and err.errno != errno.EWOULDBLOCK and err.errno != EAGAIN: raise sock2, address = listensock.accept() sock2.setblocking(0) listensock.close() return (sock1, sock2)
def send(self, data, flags=0, timeout=timeout_default): sock = self._sock if timeout is timeout_default: timeout = self.timeout try: return sock.send(data, flags) except error: ex = sys.exc_info()[1] if ex.args[0] != EWOULDBLOCK or timeout == 0.0: raise sys.exc_clear() self._wait(self._write_event) try: return sock.send(data, flags) except error: ex2 = sys.exc_info()[1] if ex2.args[0] == EWOULDBLOCK: return 0 raise
def sendto(self, *args): sock = self._sock try: return sock.sendto(*args) except error: ex = sys.exc_info()[1] if ex.args[0] != EWOULDBLOCK or timeout == 0.0: raise sys.exc_clear() self._wait(self._write_event) try: return sock.sendto(*args) except error: ex2 = sys.exc_info()[1] if ex2.args[0] == EWOULDBLOCK: return 0 raise
def recv(self, *args): sock = self._sock # keeping the reference so that fd is not closed during waiting while True: try: return sock.recv(*args) except error, ex: if ex[0] == EBADF: return '' if ex[0] != EWOULDBLOCK or self.timeout == 0.0: raise # QQQ without clearing exc_info test__refcount.test_clean_exit fails sys.exc_clear() try: wait_read(sock.fileno(), timeout=self.timeout, event=self._read_event) except error, ex: if ex[0] == EBADF: return '' raise
def recv_into(self, *args): sock = self._sock while True: try: return sock.recv_into(*args) except error, ex: if ex[0] == EBADF: return 0 if ex[0] != EWOULDBLOCK or self.timeout == 0.0: raise sys.exc_clear() try: wait_read(sock.fileno(), timeout=self.timeout, event=self._read_event) except error, ex: if ex[0] == EBADF: return 0 raise
def send(self, data, flags=0, timeout=timeout_default): sock = self._sock if timeout is timeout_default: timeout = self.timeout try: return sock.send(data, flags) except error, ex: if ex[0] != EWOULDBLOCK or timeout == 0.0: raise sys.exc_clear() try: wait_write(sock.fileno(), timeout=timeout, event=self._write_event) except error, ex: if ex[0] == EBADF: return 0 raise try: return sock.send(data, flags) except error, ex2: if ex2[0] == EWOULDBLOCK: return 0 raise
def run_for_multiple(self, timeout): while self.alive: self.notify() try: ready = self.wait(timeout) except StopWaiting: return if ready is not None: for listener in ready: try: self.accept(listener) except socket.error as e: if e.args[0] not in (errno.EAGAIN, errno.ECONNABORTED, errno.EWOULDBLOCK): raise if not self.is_parent_alive(): return
def _read(self): try: buf = self.sock.recv(self.MAX_IO_CHUNK) except socket.timeout: return except socket.error: ex = sys.exc_info()[1] if get_exc_errno(ex) in (errno.EAGAIN, errno.EWOULDBLOCK): # windows just has to be a bitch return self.close() raise EOFError(ex) if not buf: self.close() raise EOFError("connection closed by peer") self.buf_in.write(BYTES_LITERAL(buf))
def _poll_read(self, timeout=None): if not self.client_side: return self.upstream.wait(timeout) self.sock.settimeout(timeout) try: buf, addr=self.sock.recvfrom(self.MAX_IO_CHUNK) except socket.timeout: self.total_timeout+=timeout if self.total_timeout>300: self.sock.close() # too much inactivity, disconnect to let it reconnect return False except socket.error: ex = sys.exc_info()[1] if get_exc_errno(ex) in (errno.EAGAIN, errno.EWOULDBLOCK): # windows just has to be a bitch return True self.close() raise EOFError(ex) if not buf: self.close() raise EOFError("connection closed by peer") self.buf_in.write(BYTES_LITERAL(buf)) self.total_timeout=0 return True
def test_timeout_connect_ex(self): # Issue #12065: on a timeout, connect_ex() should return the original # errno (mimicking the behaviour of non-SSL sockets). with support.transient_internet("svn.python.org"): s = ssl.wrap_socket(socket.socket(socket.AF_INET), cert_reqs=ssl.CERT_REQUIRED, ca_certs=SVN_PYTHON_ORG_ROOT_CERT, do_handshake_on_connect=False) try: s.settimeout(0.0000001) rc = s.connect_ex(('svn.python.org', 443)) if rc == 0: self.skipTest("svn.python.org responded too quickly") self.assertIn(rc, (errno.EAGAIN, errno.EWOULDBLOCK)) finally: s.close()
def reset_input_buffer(self): """Clear input buffer, discarding all that is in the buffer.""" if not self.is_open: raise portNotOpenError # just use recv to remove input, while there is some ready = True while ready: ready, _, _ = select.select([self._socket], [], [], 0) try: self._socket.recv(4096) except OSError as e: # this is for Python 3.x where select.error is a subclass of # OSError ignore BlockingIOErrors and EINTR. other errors are shown # https://www.python.org/dev/peps/pep-0475. if e.errno not in (errno.EAGAIN, errno.EALREADY, errno.EWOULDBLOCK, errno.EINPROGRESS, errno.EINTR): raise SerialException('read failed: {}'.format(e)) except (select.error, socket.error) as e: # this is for Python 2.x # ignore BlockingIOErrors and EINTR. all errors are shown # see also http://www.python.org/dev/peps/pep-3151/#select if e[0] not in (errno.EAGAIN, errno.EALREADY, errno.EWOULDBLOCK, errno.EINPROGRESS, errno.EINTR): raise SerialException('read failed: {}'.format(e))
def run_for_multiple(self, timeout): while self.alive: self.notify() try: ready = self.wait(timeout) except StopWaiting: return if ready is not None: for listener in ready: if listener == self.PIPE[0]: continue try: self.accept(listener) except EnvironmentError as e: if e.errno not in (errno.EAGAIN, errno.ECONNABORTED, errno.EWOULDBLOCK): raise if not self.is_parent_alive(): return
def __init__(self, head = HEAD_WORD_LSB): self.sock = None # socket object self.send_buf = '' # send buffer self.recv_buf = '' # recv buffer self.state = NET_STATE_STOP self.errd = [ errno.EINPROGRESS, errno.EALREADY, errno.EWOULDBLOCK ] self.conn = ( errno.EISCONN, 10057, 10053 ) self.errc = 0 self.headmsk = False self.headraw = False self.__head_init(head) self.crypts = None self.cryptr = None self.ipv6 = False self.eintr = () if 'EINTR' in errno.__dict__: self.eintr = (errno.__dict__['EINTR'],) if 'WSAEWOULDBLOCK' in errno.__dict__: self.errd.append(errno.WSAEWOULDBLOCK) self.errd = tuple(self.errd) self.block = False
def test_timeout_connect_ex(self): # Issue #12065: on a timeout, connect_ex() should return the original # errno (mimicking the behaviour of non-SSL sockets). with support.transient_internet(REMOTE_HOST): s = ssl.wrap_socket(socket.socket(socket.AF_INET), cert_reqs=ssl.CERT_REQUIRED, ca_certs=REMOTE_ROOT_CERT, do_handshake_on_connect=False) try: s.settimeout(0.0000001) rc = s.connect_ex((REMOTE_HOST, 443)) if rc == 0: self.skipTest("REMOTE_HOST responded too quickly") self.assertIn(rc, (errno.EAGAIN, errno.EWOULDBLOCK)) finally: s.close()
def test_connect_ex_error(self): with support.transient_internet(REMOTE_HOST): s = ssl.wrap_socket(socket.socket(socket.AF_INET), cert_reqs=ssl.CERT_REQUIRED, ca_certs=REMOTE_ROOT_CERT) try: rc = s.connect_ex((REMOTE_HOST, 444)) # Issue #19919: Windows machines or VMs hosted on Windows # machines sometimes return EWOULDBLOCK. errors = ( errno.ECONNREFUSED, errno.EHOSTUNREACH, errno.ETIMEDOUT, errno.EWOULDBLOCK, ) self.assertIn(rc, errors) finally: s.close()
def run(self): self.before_actions() # Make non-blocking so self.stop has effect self.sock.setblocking(0) while not self.stopped: try: self.action() except socket.error as error: if error.args[0] == errno.EWOULDBLOCK: # No data available, wait a bit time.sleep(0.2) continue # Might be connection error self.stop() self.on_error() self.after_actions() self.sock.close()