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))
python类EALREADY的实例源码
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 connectThread(self):
while not self.connected:
try:
self.client.connect((HOST, PORT))
except socket.error as e:
pass
finally:
if e.errno == errno.EINPROGRESS:
time.sleep(1.0)
elif e.errno == errno.ECONNREFUSED:
time.sleep(1.0)
elif e.errno == errno.EALREADY:
time.sleep(1.0)
elif e.errno == errno.EINVAL:
break
elif e.errno == errno.EISCONN:
logger.log("[button]: Connected to Artoo.")
self.connected = True
self.buttonsInitialized = False
else:
logger.log("[button]: Unexpected socket exception: %s" % e)
time.sleep(1.0)
def _connect(self, sock, sa):
while not self._canceled and not ABORT_FLAG_FUNCTION():
time.sleep(0.01)
self._check_timeout() # this should be done at the beginning of each loop
status = sock.connect_ex(sa)
if not status or status in (errno.EISCONN, WIN_EISCONN):
break
elif status in (errno.EINPROGRESS, WIN_EWOULDBLOCK):
self.deadline = time.time() + self._timeout.getConnectTimeout()
# elif status in (errno.EWOULDBLOCK, errno.EALREADY) or (os.name == 'nt' and status == errno.WSAEINVAL):
# pass
yield
if self._canceled or ABORT_FLAG_FUNCTION():
raise CanceledException('Request canceled')
error = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
if error:
# TODO: determine when this case can actually happen
raise socket.error((error,))
def __init__ (self):
self.sock = None # socket object
self.send_buf = [] # send buffer
self.recv_buf = [] # recv buffer
self.pend_buf = '' # send pending
self.state = NET_STATE_CLOSED
self.errd = [ errno.EINPROGRESS, errno.EALREADY, errno.EWOULDBLOCK ]
self.conn = ( errno.EISCONN, 10057, 10053 )
self.errc = 0
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.timeout = 0
self.timecon = 0
def _connect(s, address):
try:
s.connect(address)
except socket.error:
(ty, v) = sys.exc_info()[:2]
if hasattr(v, 'errno'):
v_err = v.errno
else:
v_err = v[0]
if v_err not in [errno.EINPROGRESS, errno.EWOULDBLOCK, errno.EALREADY]:
raise v
def connect(self, *addr):
timeout = self.timeout
sock = self.sock
try:
# Non-blocking mode
sock.setblocking(0)
sock.connect(*addr)
sock.setblocking(timeout != 0)
return 1
except socket.error,why:
if not timeout:
raise
sock.setblocking(1)
if len(why.args) == 1:
code = 0
else:
code, why = why
if code not in (
errno.EINPROGRESS, errno.EALREADY, errno.EWOULDBLOCK
):
raise
_,w,_ = select.select([],[sock],[],timeout)
if w:
try:
sock.connect(*addr)
return 1
except socket.error,why:
if len(why.args) == 1:
code = 0
else:
code, why = why
if code in (errno.EISCONN, WSAEINVAL):
return 1
raise
raise TimeoutError('socket connect() timeout.')
def _connect(s, address):
try:
s.connect(address)
except socket.error:
(ty, v) = sys.exc_info()[:2]
if v[0] != errno.EINPROGRESS and \
v[0] != errno.EWOULDBLOCK and \
v[0] != errno.EALREADY:
raise v
def connect(self, *addr):
timeout = self.timeout
sock = self.sock
try:
# Non-blocking mode
sock.setblocking(0)
apply(sock.connect, addr)
sock.setblocking(timeout != 0)
return 1
except socket.error,why:
if not timeout:
raise
sock.setblocking(1)
if len(why.args) == 1:
code = 0
else:
code, why = why
if code not in (
errno.EINPROGRESS, errno.EALREADY, errno.EWOULDBLOCK
):
raise
r,w,e = select.select([],[sock],[],timeout)
if w:
try:
apply(sock.connect, addr)
return 1
except socket.error,why:
if len(why.args) == 1:
code = 0
else:
code, why = why
if code in (errno.EISCONN, WSAEINVAL):
return 1
raise
raise TimeoutError('socket connect() timeout.')
def _connect(s, address):
try:
s.connect(address)
except socket.error:
(ty, v) = sys.exc_info()[:2]
if v[0] != errno.EINPROGRESS and \
v[0] != errno.EWOULDBLOCK and \
v[0] != errno.EALREADY:
raise v
def _connect(s, address):
try:
s.connect(address)
except socket.error:
(ty, v) = sys.exc_info()[:2]
if v[0] != errno.EINPROGRESS and \
v[0] != errno.EWOULDBLOCK and \
v[0] != errno.EALREADY:
raise v
def connect(self, dest):
with self.lock:
if not self.state.CLOSED:
self.err("connect() in socket state {0}".format(self.state))
if self.state.ESTABLISHED:
raise err.Error(errno.EISCONN)
if self.state.CONNECT:
raise err.Error(errno.EALREADY)
raise err.Error(errno.EPIPE)
if isinstance(dest, (bytes, bytearray)):
send_pdu = pdu.Connect(1, self.addr, self.recv_miu,
self.recv_win, bytes(dest))
elif isinstance(dest, int):
send_pdu = pdu.Connect(dest, self.addr, self.recv_miu,
self.recv_win)
else:
raise TypeError("connect destination must be int or bytes")
self.state.CONNECT = True
self.send_queue.append(send_pdu)
try:
rcvd_pdu = super(DataLinkConnection, self).recv()
except IndexError:
raise err.Error(errno.EPIPE)
if rcvd_pdu.name == "DM":
logstr = "connect rejected with reason {}"
self.log(logstr.format(rcvd_pdu.reason))
self.state.CLOSED = True
raise err.ConnectRefused(rcvd_pdu.reason)
elif rcvd_pdu.name == "CC":
self.peer = rcvd_pdu.ssap
self.recv_buf = self.recv_win
self.send_miu = rcvd_pdu.miu
self.send_win = rcvd_pdu.rw
self.state.ESTABLISHED = True
return
else: # pragma: no cover
raise RuntimeError("CC or DM expected, not " + rcvd_pdu.name)
def connect(self, address):
if self.timeout == 0.0:
return self._sock.connect(address)
sock = self._sock
if isinstance(address, tuple):
r = getaddrinfo(address[0], address[1], sock.family, sock.type, sock.proto)
address = r[0][-1]
if self.timeout is not None:
timer = Timeout.start_new(self.timeout, timeout('timed out'))
else:
timer = None
try:
while True:
err = sock.getsockopt(SOL_SOCKET, SO_ERROR)
if err:
raise error(err, strerror(err))
result = sock.connect_ex(address)
if not result or result == EISCONN:
break
elif (result in (EWOULDBLOCK, EINPROGRESS, EALREADY)) or (result == EINVAL and is_windows):
self._wait(self._write_event)
else:
raise error(result, strerror(result))
finally:
if timer is not None:
timer.cancel()
def connect(self, address):
if self.timeout == 0.0:
return self._sock.connect(address)
sock = self._sock
if isinstance(address, tuple):
r = getaddrinfo(address[0], address[1], sock.family, sock.type, sock.proto)
address = r[0][-1]
if self.timeout is not None:
timer = Timeout.start_new(self.timeout, timeout('timed out'))
else:
timer = None
try:
while True:
err = sock.getsockopt(SOL_SOCKET, SO_ERROR)
if err:
raise error(err, strerror(err))
result = sock.connect_ex(address)
if not result or result == EISCONN:
break
elif (result in (EWOULDBLOCK, EINPROGRESS, EALREADY)) or (result == EINVAL and is_windows):
self._wait(self._write_event)
else:
raise error(result, strerror(result))
finally:
if timer is not None:
timer.cancel()
def connect(self, address):
if isinstance(address, tuple) and len(address) == 2:
address = gethostbyname(address[0]), address[1]
if self.timeout == 0.0:
return self._sock.connect(address)
sock = self._sock
if self.timeout is None:
while True:
err = sock.getsockopt(SOL_SOCKET, SO_ERROR)
if err:
raise error(err, strerror(err))
result = sock.connect_ex(address)
if not result or result == EISCONN:
break
elif (result in (EWOULDBLOCK, EINPROGRESS, EALREADY)) or (result == EINVAL and is_windows):
wait_readwrite(sock.fileno(), event=self._rw_event)
else:
raise error(result, strerror(result))
else:
end = time.time() + self.timeout
while True:
err = sock.getsockopt(SOL_SOCKET, SO_ERROR)
if err:
raise error(err, strerror(err))
result = sock.connect_ex(address)
if not result or result == EISCONN:
break
elif (result in (EWOULDBLOCK, EINPROGRESS, EALREADY)) or (result == EINVAL and is_windows):
timeleft = end - time.time()
if timeleft <= 0:
raise timeout('timed out')
wait_readwrite(sock.fileno(), timeout=timeleft, event=self._rw_event)
else:
raise error(result, strerror(result))
def connect(self, *addr):
timeout = self.timeout
sock = self.sock
try:
# Non-blocking mode
sock.setblocking(0)
apply(sock.connect, addr)
sock.setblocking(timeout != 0)
return 1
except socket.error,why:
if not timeout:
raise
sock.setblocking(1)
if len(why.args) == 1:
code = 0
else:
code, why = why
if code not in (
errno.EINPROGRESS, errno.EALREADY, errno.EWOULDBLOCK
):
raise
r,w,e = select.select([],[sock],[],timeout)
if w:
try:
apply(sock.connect, addr)
return 1
except socket.error,why:
if len(why.args) == 1:
code = 0
else:
code, why = why
if code in (errno.EISCONN, WSAEINVAL):
return 1
raise
raise TimeoutError('socket connect() timeout.')
def connect(self, address):
if self.timeout == 0.0:
return self._sock.connect(address)
sock = self._sock
if isinstance(address, tuple):
r = getaddrinfo(address[0], address[1], sock.family, sock.type, sock.proto)
address = r[0][-1]
if self.timeout is not None:
timer = Timeout.start_new(self.timeout, timeout('timed out'))
else:
timer = None
try:
while True:
err = sock.getsockopt(SOL_SOCKET, SO_ERROR)
if err:
raise error(err, strerror(err))
result = sock.connect_ex(address)
if not result or result == EISCONN:
break
elif (result in (EWOULDBLOCK, EINPROGRESS, EALREADY)) or (result == EINVAL and is_windows):
self._wait(self._write_event)
else:
raise error(result, strerror(result))
finally:
if timer is not None:
timer.cancel()
def connect(self, address):
if self.timeout == 0.0:
return self._sock.connect(address)
sock = self._sock
if isinstance(address, tuple):
r = getaddrinfo(address[0], address[1], sock.family, sock.type, sock.proto)
address = r[0][-1]
if self.timeout is not None:
timer = Timeout.start_new(self.timeout, timeout('timed out'))
else:
timer = None
try:
while True:
err = sock.getsockopt(SOL_SOCKET, SO_ERROR)
if err:
raise error(err, strerror(err))
result = sock.connect_ex(address)
if not result or result == EISCONN:
break
elif (result in (EWOULDBLOCK, EINPROGRESS, EALREADY)) or (result == EINVAL and is_windows):
self._wait(self._write_event)
else:
raise error(result, strerror(result))
finally:
if timer is not None:
timer.cancel()
def connect(self, address):
if isinstance(address, tuple) and len(address) == 2:
address = gethostbyname(address[0]), address[1]
if self.timeout == 0.0:
return self._sock.connect(address)
sock = self._sock
if self.timeout is None:
while True:
err = sock.getsockopt(SOL_SOCKET, SO_ERROR)
if err:
raise error(err, strerror(err))
result = sock.connect_ex(address)
if not result or result == EISCONN:
break
elif (result in (EWOULDBLOCK, EINPROGRESS, EALREADY)) or (result == EINVAL and is_windows):
wait_readwrite(sock.fileno(), event=self._rw_event)
else:
raise error(result, strerror(result))
else:
end = time.time() + self.timeout
while True:
err = sock.getsockopt(SOL_SOCKET, SO_ERROR)
if err:
raise error(err, strerror(err))
result = sock.connect_ex(address)
if not result or result == EISCONN:
break
elif (result in (EWOULDBLOCK, EINPROGRESS, EALREADY)) or (result == EINVAL and is_windows):
timeleft = end - time.time()
if timeleft <= 0:
raise timeout('timed out')
wait_readwrite(sock.fileno(), timeout=timeleft, event=self._rw_event)
else:
raise error(result, strerror(result))
def _connect(s, address):
try:
s.connect(address)
except socket.error:
(ty, v) = sys.exc_info()[:2]
if hasattr(v, 'errno'):
v_err = v.errno
else:
v_err = v[0]
if v_err not in [errno.EINPROGRESS, errno.EWOULDBLOCK, errno.EALREADY]:
raise v
def read(self, size=1):
"""\
Read size bytes from the serial port. If a timeout is set it may
return less characters as requested. With no timeout it will block
until the requested number of bytes is read.
"""
if not self.is_open:
raise portNotOpenError
read = bytearray()
timeout = Timeout(self._timeout)
while len(read) < size:
try:
ready, _, _ = select.select([self._socket], [], [], timeout.time_left())
# If select was used with a timeout, and the timeout occurs, it
# returns with empty lists -> thus abort read operation.
# For timeout == 0 (non-blocking operation) also abort when
# there is nothing to read.
if not ready:
break # timeout
buf = self._socket.recv(size - len(read))
# read should always return some data as select reported it was
# ready to read when we get to this point, unless it is EOF
if not buf:
raise SerialException('socket disconnected')
read.extend(buf)
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))
if timeout.expired():
break
return bytes(read)
def connect(self, *addr):
timeout = self.timeout
sock = self.sock
try:
# Non-blocking mode
sock.setblocking(0)
apply(sock.connect, addr)
sock.setblocking(timeout != 0)
return 1
except socket.error,why:
if not timeout:
raise
sock.setblocking(1)
if len(why.args) == 1:
code = 0
else:
code, why = why
if code not in (
errno.EINPROGRESS, errno.EALREADY, errno.EWOULDBLOCK
):
raise
r,w,e = select.select([],[sock],[],timeout)
if w:
try:
apply(sock.connect, addr)
return 1
except socket.error,why:
if len(why.args) == 1:
code = 0
else:
code, why = why
if code in (errno.EISCONN, WSAEINVAL):
return 1
raise
raise TimeoutError('socket connect() timeout.')
def _connect(s, address):
try:
s.connect(address)
except socket.error:
(ty, v) = sys.exc_info()[:2]
if hasattr(v, 'errno'):
v_err = v.errno
else:
v_err = v[0]
if v_err not in [errno.EINPROGRESS, errno.EWOULDBLOCK, errno.EALREADY]:
raise v
def connect(self, dest):
with self.lock:
if not self.state.CLOSED:
self.err("connect() in socket state {0}".format(self.state))
if self.state.ESTABLISHED:
raise Error(errno.EISCONN)
if self.state.CONNECT:
raise Error(errno.EALREADY)
raise Error(errno.EPIPE)
if type(dest) is StringType:
pdu = Connect(1, self.addr, self.recv_miu, self.recv_win, dest)
elif type(dest) is IntType:
pdu = Connect(dest, self.addr, self.recv_miu, self.recv_win)
else: raise TypeError("connect() arg *dest* must be int or string")
self.state.CONNECT = True
self.send_queue.append(pdu)
try: pdu = super(DataLinkConnection, self).recv()
except IndexError: raise Error(errno.EPIPE)
if isinstance(pdu, DisconnectedMode):
self.log("connect rejected with reason {0}".format(pdu.reason))
self.state.CLOSED = True
raise ConnectRefused(pdu.reason)
if isinstance(pdu, ConnectionComplete):
self.peer = pdu.ssap
self.recv_buf = self.recv_win
self.send_miu = pdu.miu
self.send_win = pdu.rw
self.state.ESTABLISHED = True
return
raise RuntimeError("only CC or DM expected, not " + pdu.name)
def _connect(s, address):
try:
s.connect(address)
except socket.error:
(ty, v) = sys.exc_info()[:2]
if v[0] != errno.EINPROGRESS and \
v[0] != errno.EWOULDBLOCK and \
v[0] != errno.EALREADY:
raise v
def connect(self, *addr):
timeout = self.timeout
sock = self.sock
try:
# Non-blocking mode
sock.setblocking(0)
apply(sock.connect, addr)
sock.setblocking(timeout != 0)
return 1
except socket.error,why:
if not timeout:
raise
sock.setblocking(1)
if len(why.args) == 1:
code = 0
else:
code, why = why
if code not in (
errno.EINPROGRESS, errno.EALREADY, errno.EWOULDBLOCK
):
raise
r,w,e = select.select([],[sock],[],timeout)
if w:
try:
apply(sock.connect, addr)
return 1
except socket.error,why:
if len(why.args) == 1:
code = 0
else:
code, why = why
if code in (errno.EISCONN, WSAEINVAL):
return 1
raise
raise TimeoutError('socket connect() timeout.')
def connect(self, *addr):
timeout = self.timeout
sock = self.sock
try:
# Non-blocking mode
sock.setblocking(0)
apply(sock.connect, addr)
sock.setblocking(timeout != 0)
return 1
except socket.error,why:
if not timeout:
raise
sock.setblocking(1)
if len(why.args) == 1:
code = 0
else:
code, why = why
if code not in (
errno.EINPROGRESS, errno.EALREADY, errno.EWOULDBLOCK
):
raise
r,w,e = select.select([],[sock],[],timeout)
if w:
try:
apply(sock.connect, addr)
return 1
except socket.error,why:
if len(why.args) == 1:
code = 0
else:
code, why = why
if code in (errno.EISCONN, WSAEINVAL):
return 1
raise
raise TimeoutError('socket connect() timeout.')
def connect(self, *addr):
timeout = self.timeout
sock = self.sock
try:
# Non-blocking mode
sock.setblocking(0)
apply(sock.connect, addr)
sock.setblocking(timeout != 0)
return 1
except socket.error,why:
if not timeout:
raise
sock.setblocking(1)
if len(why.args) == 1:
code = 0
else:
code, why = why
if code not in (
errno.EINPROGRESS, errno.EALREADY, errno.EWOULDBLOCK
):
raise
r,w,e = select.select([],[sock],[],timeout)
if w:
try:
apply(sock.connect, addr)
return 1
except socket.error,why:
if len(why.args) == 1:
code = 0
else:
code, why = why
if code in (errno.EISCONN, WSAEINVAL):
return 1
raise
raise TimeoutError('socket connect() timeout.')
query.py 文件源码
项目:Infrax-as-Code-1000-webservers-in-40-minutes
作者: ezeeetm
项目源码
文件源码
阅读 28
收藏 0
点赞 0
评论 0
def _connect(s, address):
try:
s.connect(address)
except socket.error:
(ty, v) = sys.exc_info()[:2]
if hasattr(v, 'errno'):
v_err = v.errno
else:
v_err = v[0]
if v_err not in [errno.EINPROGRESS, errno.EWOULDBLOCK, errno.EALREADY]:
raise v
def connect(self, address):
if self.timeout == 0.0:
return self._sock.connect(address)
sock = self._sock
if isinstance(address, tuple):
r = getaddrinfo(address[0], address[1], sock.family, sock.type, sock.proto)
address = r[0][-1]
if self.timeout is not None:
timer = Timeout.start_new(self.timeout, timeout('timed out'))
else:
timer = None
try:
while True:
err = sock.getsockopt(SOL_SOCKET, SO_ERROR)
if err:
raise error(err, strerror(err))
result = sock.connect_ex(address)
if not result or result == EISCONN:
break
elif (result in (EWOULDBLOCK, EINPROGRESS, EALREADY)) or (result == EINVAL and is_windows):
self._wait(self._write_event)
else:
raise error(result, strerror(result))
finally:
if timer is not None:
timer.cancel()