本文整理汇总了Python中socket.timeout函数的典型用法代码示例。如果您正苦于以下问题:Python timeout函数的具体用法?Python timeout怎么用?Python timeout使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了timeout函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: connect_ex
def connect_ex(self, address):
if self.act_non_blocking:
return self.fd.connect_ex(address)
fd = self.fd
if self.gettimeout() is None:
while not socket_connect(fd, address):
try:
self._trampoline(fd, write=True)
socket_checkerr(fd)
except socket.error as ex:
return get_errno(ex)
except IOClosed:
return errno.EBADFD
else:
end = time.time() + self.gettimeout()
while True:
try:
if socket_connect(fd, address):
return 0
if time.time() >= end:
raise socket.timeout(errno.EAGAIN)
self._trampoline(fd, write=True, timeout=end - time.time(),
timeout_exc=socket.timeout(errno.EAGAIN))
socket_checkerr(fd)
except socket.error as ex:
return get_errno(ex)
except IOClosed:
return errno.EBADFD
示例2: recv
def recv(self, bufsize, flags=0):
"""
Use select() to simulate a socket timeout without setting the socket
to non-blocking mode
"""
timeout = self.__dict__["timeout"]
con = self.__dict__["conn"]
(read, write, excpt) = select.select([con], [], [], timeout)
if not con in read:
raise socket.timeout((110, "Operation timed out."))
starttime = time.time()
while True:
curtime = time.time()
if curtime - starttime > timeout:
raise socket.timeout((110, "Operation timed out."))
try:
return con.recv(bufsize, flags)
except SSL.ZeroReturnError:
return None
except SSL.WantReadError:
time.sleep(0.2)
except Exception, e:
if canIgnoreSSLError(e):
return None
else:
raise e
示例3: connect
def connect(self, address):
if self.act_non_blocking:
return self.fd.connect(address)
fd = self.fd
if self.gettimeout() is None:
while not socket_connect(fd, address):
try:
self._trampoline(fd, write=True)
except IOClosed:
raise socket.error(errno.EBADFD)
socket_checkerr(fd)
else:
end = time.time() + self.gettimeout()
while True:
if socket_connect(fd, address):
return
if time.time() >= end:
raise socket.timeout("timed out")
try:
self._trampoline(fd, write=True, timeout=end - time.time(),
timeout_exc=socket.timeout("timed out"))
except IOClosed:
# ... we need some workable errno here.
raise socket.error(errno.EBADFD)
socket_checkerr(fd)
示例4: _check_timeout
def _check_timeout(self):
self._lock()
conns = self._sock_dict.values()
self._unlock()
now = self.get_time()
# the socking listening is not in _sock_dict, so it'll not be touched
self._last_checktimeout = now
for conn in conns:
inact_time = now - conn.last_ts
if conn.status_rd == ConnState.IDLE and self._idle_timeout > 0 and inact_time > self._idle_timeout:
if callable(conn.idle_timeout_cb):
conn.error = socket.timeout("idle timeout")
conn.idle_timeout_cb(conn, *conn.readable_cb_args)
self.close_conn(conn)
elif conn.status_rd == ConnState.TOREAD and self._rw_timeout > 0 and inact_time > self._rw_timeout:
if callable(conn.read_err_cb):
conn.error = socket.timeout("read timeout")
self._exec_callback(
conn.read_err_cb, (conn,) + conn.read_cb_args, conn.read_tb)
self.close_conn(conn)
elif conn.status_wr == ConnState.TOWRITE and self._rw_timeout > 0 and inact_time > self._rw_timeout:
if callable(conn.write_err_cb):
conn.error = socket.timeout("write timeout")
self._exec_callback(
conn.write_err_cb, (conn,) + conn.write_cb_args, conn.write_tb)
self.close_conn(conn)
示例5: blocking_read
def blocking_read(self, timeout=None):
read_frame = self.transport.read_frame
if timeout is None:
return self.on_inbound_frame(read_frame())
# XXX use select
sock = self.sock
prev = sock.gettimeout()
if prev != timeout:
sock.settimeout(timeout)
try:
try:
frame = read_frame()
except SSLError as exc:
# http://bugs.python.org/issue10272
if 'timed out' in str(exc):
raise socket.timeout()
# Non-blocking SSL sockets can throw SSLError
if 'The operation did not complete' in str(exc):
raise socket.timeout()
raise
else:
self.on_inbound_frame(frame)
finally:
if prev != timeout:
sock.settimeout(prev)
示例6: chk_con
def chk_con(kms):
#parse kms
hostname = None
port = None
result = None
ip = None
ipaddr = None
hostname = re.search('https://(.*?):',kms[0],flags=0).group(1)
logging.info('KMS FQDN : %s' %hostname)
port = re.search('https://.*:(.*)/',kms[0],flags=0).group(1)
logging.info ('KMS WebAPI Port : %s' %port)
#DNS resolve
try:
socket.gethostbyname(hostname)
except :
logging.error('DNS resolve problem for this KMS server FQDN : %s' %hostname)
print '!!! DNS resolve issue for FQDN : %s!!!' %hostname
return (False)
else :
result = socket.gethostbyaddr(hostname)
ip = result[2]
ipaddr = ip[0]
logging.info('KMS IP address : %s' %ipaddr)
#TCP connect
socket.timeout(30)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect((ipaddr,int(port)))
except Exception, e:
logging.exception('TCP connection error with %s:%d. Exception type is %s' % (ipaddr, int(port), `e`))
print 'TCP connection error with KMS server %s port %d. Error type %s'% (ipaddr, int(port), `e`)
return (False)
示例7: test_new_crash_with_fail_retry
def test_new_crash_with_fail_retry(self):
config = self._setup_config()
config.transaction_executor_class = \
TransactionExecutorWithInfiniteBackoff
crash_store = RabbitMQCrashStorage(config)
iterable = [
('1', '1', 'crash_id'),
timeout(),
timeout(),
('2', '2', 'other_id')
]
def an_iterator(queue):
item = iterable.pop()
if isinstance(item, Exception):
raise item
return item
crash_store.rabbitmq.operational_exceptions = (
timeout,
)
crash_store.rabbitmq.return_value.__enter__.return_value \
.channel.basic_get = MagicMock(side_effect=an_iterator)
expected = ('other_id', 'crash_id', )
for expected, result in zip(expected, crash_store.new_crashes()):
eq_(expected, result)
示例8: having_timeout
def having_timeout(self, timeout):
if timeout is None:
yield self.sock
else:
sock = self.sock
prev = sock.gettimeout()
if prev != timeout:
sock.settimeout(timeout)
try:
yield self.sock
except SSLError as exc:
if 'timed out' in str(exc):
# http://bugs.python.org/issue10272
raise socket.timeout()
elif 'The operation did not complete' in str(exc):
# Non-blocking SSL sockets can throw SSLError
raise socket.timeout()
raise
except socket.error as exc:
if get_errno(exc) == errno.EWOULDBLOCK:
raise socket.timeout()
raise
finally:
if timeout != prev:
sock.settimeout(prev)
示例9: _check_timeout
def _check_timeout (self):
self._lock ()
conns = self._sock_dict.values ()
self._unlock ()
now = self.get_time ()
#the socking listening is not in _sock_dict, so it'll not be touched
self._last_checktimeout = now
def __is_timeout (conn):
inact_time = now - conn.last_ts
if conn.status == ConnState.IDLE and self._idle_timeout > 0 and inact_time > self._idle_timeout:
return True
elif (conn.status == ConnState.TOREAD or conn.status == ConnState.TOWRITE) \
and self._rw_timeout > 0 and inact_time > self._rw_timeout:
return True
return False
timeout_list = filter (__is_timeout, conns)
for conn in timeout_list:
if conn.status == ConnState.IDLE:
if callable (conn.idle_timeout_cb):
conn.error = socket.timeout ("idle timeout")
conn.idle_timeout_cb (conn, *conn.readable_cb_args)
elif callable(conn.unblock_err_cb):
conn.error = socket.timeout ("timeout")
self._exec_callback (conn.unblock_err_cb, (conn,) + conn.unblock_cb_args, conn.unblock_tb)
self._close_conn (conn)
示例10: _safe_ssl_call
def _safe_ssl_call(suppress_ragged_eofs, sock, call, *args, **kwargs):
"""Wrap the given call with SSL error-trapping."""
start = time.time()
while True:
try:
return getattr(sock, call)(*args, **kwargs)
except (ossl.WantReadError, ossl.WantWriteError):
if select is None:
if time.time() - start > sock.gettimeout():
raise socket.timeout()
time.sleep(SSL_RETRY)
elif not select.select([sock], [], [], sock.gettimeout())[0]:
raise socket.timeout()
except ossl.SysCallError as e:
if suppress_ragged_eofs and e.args[0] == (-1, 'Unexpected EOF'):
return b''
elif e.args[0] == 0:
raise SSLEOFError(*e.args)
raise SSLSysCallError(*e.args)
except ossl.ZeroReturnError as e:
raise SSLZeroReturnError(*e.args)
except ossl.Error as e:
raise SSLError(*e.args)
示例11: sendall
def sendall(self, data, flags=0):
"""
- Use select() to simulate a socket timeout without setting the socket
to non-blocking mode.
- Don't use pyOpenSSL's sendall() either, since it just loops on WantRead
or WantWrite, consuming 100% CPU, and never times out.
"""
timeout = self.__dict__["timeout"]
con = self.__dict__["conn"]
(read, write, excpt) = select.select([], [con], [], timeout)
if not con in write:
raise socket.timeout((110, "Operation timed out."))
starttime = time.time()
origlen = len(data)
sent = -1
while len(data):
curtime = time.time()
if curtime - starttime > timeout:
raise socket.timeout((110, "Operation timed out."))
try:
sent = con.send(data, flags)
except SSL.SysCallError, e:
if e[0] == 32: # Broken Pipe
self.close()
sent = 0
else:
raise socket.error(e)
except (SSL.WantWriteError, SSL.WantReadError):
time.sleep(0.2)
continue
示例12: _read
def _read(self, n, initial=False,
_errnos=(errno.ENOENT, errno.EAGAIN, errno.EINTR)):
# According to SSL_read(3), it can at most return 16kb of data.
# Thus, we use an internal read buffer like TCPTransport._read
# to get the exact number of bytes wanted.
recv = self._quick_recv
rbuf = self._read_buffer
try:
while len(rbuf) < n:
try:
s = recv(n - len(rbuf)) # see note above
except socket.error as exc:
# ssl.sock.read may cause a SSLerror without errno
# http://bugs.python.org/issue10272
if isinstance(exc, SSLError) and 'timed out' in str(exc):
raise socket.timeout()
# ssl.sock.read may cause ENOENT if the
# operation couldn't be performed (Issue celery#1414).
if exc.errno in _errnos:
if initial and self.raise_on_initial_eintr:
raise socket.timeout()
continue
raise
if not s:
raise IOError('Server unexpectedly closed connection')
rbuf += s
except: # noqa
self._read_buffer = rbuf
raise
result, self._read_buffer = rbuf[:n], rbuf[n:]
return result
示例13: recv
def recv(self, nbytes):
"""
Receive data from the channel. The return value is a string
representing the data received. The maximum amount of data to be
received at once is specified by C{nbytes}. If a string of length zero
is returned, the channel stream has closed.
@param nbytes: maximum number of bytes to read.
@type nbytes: int
@return: data.
@rtype: str
@raise socket.timeout: if no data is ready before the timeout set by
L{settimeout}.
"""
out = ''
self.lock.acquire()
try:
if len(self.in_buffer) == 0:
if self.closed or self.eof_received:
return out
# should we block?
if self.timeout == 0.0:
raise socket.timeout()
# loop here in case we get woken up but a different thread has grabbed everything in the buffer
timeout = self.timeout
while (len(self.in_buffer) == 0) and not self.closed and not self.eof_received:
then = time.time()
self.in_buffer_cv.wait(timeout)
if timeout != None:
timeout -= time.time() - then
if timeout <= 0.0:
raise socket.timeout()
# something in the buffer and we have the lock
if len(self.in_buffer) <= nbytes:
out = self.in_buffer
self.in_buffer = ''
if self.pipe is not None:
# clear the pipe, since no more data is buffered
self.pipe.clear()
else:
out = self.in_buffer[:nbytes]
self.in_buffer = self.in_buffer[nbytes:]
ack = self._check_add_window(len(out))
finally:
self.lock.release()
# no need to hold the channel lock when sending this
if ack > 0:
m = Message()
m.add_byte(chr(MSG_CHANNEL_WINDOW_ADJUST))
m.add_int(self.remote_chanid)
m.add_int(ack)
self.transport._send_user_message(m)
return out
示例14: getTime
def getTime():
TIME_1970 = 2208988800L
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
socket.timeout(5)
data = '\x1b' + 47 * '\0'
client.sendto(data, (TimeServer, Port))
data, address = client.recvfrom(1024)
data_result = struct.unpack('!12I', data)[10]
data_result -= TIME_1970
return data_result
示例15: HttpPostData
def HttpPostData(postdata):
socket.timeout(HTTPTIMEOUT)
try:
headers = {"Content-type": "application/json", "Accept": "application/json", "Authorization": AUTHTOKEN}
req = urllib2.Request(SOSSERVER + SOSJSON, postdata, headers)
response = urllib2.urlopen(req)
return response.read()
except urllib2.HTTPError as e:
print ' error: ' + str(e.code)
return "ERROR:HTTP " + str(e.code)