Commit 5c11789c authored by Denis Bilenko's avatar Denis Bilenko

gevent package: (some) py3k compatibility. Original patches by Damien Churchill.

- define basestring in hub.py for version that don't have it
- use exc_info()
- define exc_clear() in hub.py as no-op
- use "exec (xxx)" instead of "exec xxx"
parent b0af1ee6
......@@ -3,6 +3,7 @@
from gevent.greenlet import Greenlet, getfuncname
from gevent.event import Event
import _socket
import sys
__all__ = ['BaseServer']
......@@ -94,7 +95,8 @@ class BaseServer(object):
if hasattr(self, 'socket'):
try:
fileno = self.socket.fileno()
except Exception, ex:
except Exception:
ex = sys.exc_info()[1]
fileno = str(ex)
result = 'fileno=%s ' % fileno
else:
......@@ -104,7 +106,8 @@ class BaseServer(object):
result += 'address=%s:%s' % self.address
else:
result += 'address=%s' % (self.address, )
except Exception, ex:
except Exception:
ex = sys.exc_info()[1]
result += str(ex) or '<error>'
try:
handle = getfuncname(self.__dict__['handle'])
......@@ -204,7 +207,8 @@ def _tcp_listener(address, backlog=50, reuse_addr=None):
sock.setsockopt(_socket.SOL_SOCKET, _socket.SO_REUSEADDR, reuse_addr)
try:
sock.bind(address)
except _socket.error, ex:
except _socket.error:
ex = sys.exc_info()[1]
strerror = getattr(ex, 'strerror', None)
if strerror is not None:
ex.strerror = strerror + ': ' + repr(address)
......
......@@ -78,7 +78,8 @@ class Semaphore(object):
try:
result = self.hub.switch()
assert result is self, 'Invalid switch into Semaphore.wait(): %r' % (result, )
except Timeout, ex:
except Timeout:
ex = sys.exc_info()[1]
if ex is not timer:
raise
finally:
......@@ -102,7 +103,8 @@ class Semaphore(object):
try:
result = self.hub.switch()
assert result is self, 'Invalid switch into Semaphore.acquire(): %r' % (result, )
except Timeout, ex:
except Timeout:
ex = sys.exc_info()[1]
if ex is timer:
return False
raise
......
......@@ -74,7 +74,8 @@ class Event(object):
try:
result = self.hub.switch()
assert result is self, 'Invalid switch into Event.wait(): %r' % (result, )
except Timeout, ex:
except Timeout:
ex = sys.exc_info()[1]
if ex is not timer:
raise
finally:
......@@ -255,7 +256,8 @@ class AsyncResult(object):
assert result is self, 'Invalid switch into AsyncResult.wait(): %r' % (result, )
finally:
timer.cancel()
except Timeout, exc:
except Timeout:
exc = sys.exc_info()[1]
self.unlink(switch)
if exc is not timer:
raise
......
......@@ -345,9 +345,9 @@ class Greenlet(greenlet):
assert result is self, 'Invalid switch into Greenlet.join(): %r' % (result, )
finally:
t.cancel()
except Timeout, ex:
except Timeout:
self.unlink(switch)
if ex is not t:
if sys.exc_info()[1] is not t:
raise
except:
self.unlink(switch)
......
......@@ -35,7 +35,10 @@ except ImportError:
getcurrent = greenlet.getcurrent
GreenletExit = greenlet.GreenletExit
thread = __import__('thread')
if sys.version_info[0] <= 2:
thread = __import__('thread')
else:
thread = __import__('_thread')
threadlocal = thread._local
_threadlocal = threadlocal()
_threadlocal.Hub = None
......@@ -176,14 +179,24 @@ def set_hub(hub):
_threadlocal.hub = hub
if sys.version_info[0] >= 3:
basestring = (str, bytes)
def exc_clear():
pass
else:
basestring = basestring
exc_clear = sys.exc_clear
def _import(path):
if isinstance(path, list):
error = ImportError('Cannot import from empty list: %r' % (path, ))
for item in path:
try:
return _import(item)
except ImportError, ex:
error = ex
except ImportError:
error = sys.exc_info()[1]
raise error
if not isinstance(path, basestring):
return path
......@@ -253,7 +266,7 @@ class Hub(greenlet):
switch_out()
except:
self.handle_error(switch_out, *sys.exc_info())
sys.exc_clear()
exc_clear()
return greenlet.switch(self)
finally:
core.set_exc_info(exc_type, exc_value)
......
......@@ -9,6 +9,8 @@ concurrency: its :meth:`spawn <Pool.spawn>` method blocks if the number of
greenlets in the pool has already reached the limit, until there is a free slot.
"""
import sys
from gevent.hub import GreenletExit, getcurrent
from gevent.greenlet import joinall, Greenlet
from gevent.timeout import Timeout
......@@ -114,7 +116,8 @@ class Group(object):
if not block:
break
joinall(self.greenlets)
except Timeout, ex:
except Timeout:
ex = sys.exc_info()[1]
if ex is not timer:
raise
finally:
......
......@@ -300,7 +300,8 @@ class WSGIHandler(object):
try:
if not self.read_request(raw_requestline):
return ('400', _BAD_REQUEST_RESPONSE)
except Exception, ex:
except Exception:
ex = sys.exc_info()[1]
if not isinstance(ex, ValueError):
traceback.print_exc()
self.log_error('Invalid request: %s', str(ex) or ex.__class__.__name__)
......@@ -310,9 +311,10 @@ class WSGIHandler(object):
self.application = self.server.application
try:
self.handle_one_response()
except socket.error, ex:
except socket.error:
ex = sys.exc_info()[1]
# Broken pipe, connection reset by peer
if ex[0] in (errno.EPIPE, errno.ECONNRESET):
if ex.args[0] in (errno.EPIPE, errno.ECONNRESET):
sys.exc_clear()
else:
raise
......
......@@ -30,7 +30,13 @@ means repeatedly calling :meth:`get <Queue.get>` until :meth:`get <Queue.get>` r
import sys
import heapq
import collections
from Queue import Full, Empty
try:
from Queue import Full, Empty
except ImportError:
__queue__ = __import__('queue')
Full = __queue__.Full
Empty = __queue__.Empty
from gevent.timeout import Timeout
from gevent.hub import get_hub, Waiter, getcurrent, _NONE
......
import os
import sys
from _socket import getservbyname, getaddrinfo, gaierror, error
from gevent.hub import Waiter, get_hub
from gevent.hub import Waiter, get_hub, basestring
from gevent.socket import AF_UNSPEC, AF_INET, AF_INET6, SOCK_STREAM, SOCK_DGRAM, SOCK_RAW, AI_NUMERICHOST, EAI_SERVICE
from gevent.ares import channel
......@@ -69,7 +70,8 @@ class Resolver(object):
port = getservbyname(port, 'udp')
else:
raise gaierror(EAI_SERVICE, 'Servname not supported for ai_socktype')
except error, ex:
except error:
ex = sys.exc_info()[1]
if 'not found' in str(ex):
raise gaierror(EAI_SERVICE, 'Servname not supported for ai_socktype')
else:
......@@ -150,7 +152,8 @@ class Resolver(object):
self.ares.gethostbyaddr(waiter, ip_address)
try:
return waiter.get()
except ValueError, ex:
except ValueError:
ex = sys.exc_info()[1]
if not str(ex).startswith('illegal IP'):
raise
# socket.gethostbyaddr also accepts domain names; let's do that too
......@@ -175,7 +178,8 @@ class Resolver(object):
self.ares.getnameinfo(waiter, sockaddr, flags)
try:
result = waiter.get()
except ValueError, ex:
except ValueError:
ex = sys.exc_info()[1]
if not str(ex).startswith('illegal IP'):
raise
# socket.getnameinfo also accepts domain names; let's do that too
......
# Copyright (c) 2009-2010 Denis Bilenko. See LICENSE for details.
import sys
from gevent.timeout import Timeout
from gevent.event import Event
from gevent.hub import get_hub
......@@ -63,7 +63,8 @@ def select(rlist, wlist, xlist, timeout=None):
watcher.priority = MAXPRI
watcher.start(result.add_write, writefd)
watchers.append(watcher)
except IOError, ex:
except IOError:
ex = sys.exc_info()[1]
raise error(*ex.args)
result.event.wait(timeout=timeout)
return result.read, result.write, []
......
......@@ -78,6 +78,8 @@ __imports__ = ['error',
import sys
import time
from gevent.hub import get_hub, basestring
from gevent.timeout import Timeout
is_windows = sys.platform == 'win32'
......@@ -124,9 +126,6 @@ for name in __socket__.__all__:
del name, value
from gevent.hub import get_hub
from gevent.timeout import Timeout
def wait(io, timeout=None, timeout_exc=timeout('timed out')):
"""Block the current greenlet until *io* is ready.
......@@ -276,8 +275,8 @@ class socket(object):
def _formatinfo(self):
try:
fileno = self.fileno()
except Exception, ex:
fileno = str(ex)
except Exception:
fileno = str(sys.exc_info()[1])
try:
sockname = self.getsockname()
sockname = '%s:%s' % sockname
......@@ -322,7 +321,8 @@ class socket(object):
try:
client_socket, address = sock.accept()
break
except error, ex:
except error:
ex = sys.exc_info()[1]
if ex[0] != EWOULDBLOCK or self.timeout == 0.0:
raise
sys.exc_clear()
......@@ -370,9 +370,10 @@ class socket(object):
return self.connect(address) or 0
except timeout:
return EAGAIN
except error, ex:
except error:
ex = sys.exc_info()[1]
if type(ex) is error:
return ex[0]
return ex.args[0]
else:
raise # gaierror is not silented by connect_ex
......@@ -393,17 +394,19 @@ class socket(object):
while True:
try:
return sock.recv(*args)
except error, ex:
if ex[0] == EBADF:
except error:
ex = sys.exc_info()[1]
if ex.args[0] == EBADF:
return ''
if ex[0] != EWOULDBLOCK or self.timeout == 0.0:
if ex.args[0] != EWOULDBLOCK or self.timeout == 0.0:
raise
# QQQ without clearing exc_info test__refcount.test_clean_exit fails
sys.exc_clear()
try:
self._wait(self._read_event)
except error, ex:
if ex[0] == EBADF:
except error:
ex = sys.exc_info()[1]
if ex.args[0] == EBADF:
return ''
raise
......@@ -412,8 +415,9 @@ class socket(object):
while True:
try:
return sock.recvfrom(*args)
except error, ex:
if ex[0] != EWOULDBLOCK or self.timeout == 0.0:
except error:
ex = sys.exc_info()[1]
if ex.args[0] != EWOULDBLOCK or self.timeout == 0.0:
raise
sys.exc_clear()
self._wait(self._read_event)
......@@ -423,8 +427,9 @@ class socket(object):
while True:
try:
return sock.recvfrom_into(*args)
except error, ex:
if ex[0] != EWOULDBLOCK or self.timeout == 0.0:
except error:
ex = sys.exc_info()[1]
if ex.args[0] != EWOULDBLOCK or self.timeout == 0.0:
raise
sys.exc_clear()
self._wait(self._read_event)
......@@ -434,16 +439,18 @@ class socket(object):
while True:
try:
return sock.recv_into(*args)
except error, ex:
if ex[0] == EBADF:
except error:
ex = sys.exc_info()[1]
if ex.args[0] == EBADF:
return 0
if ex[0] != EWOULDBLOCK or self.timeout == 0.0:
if ex.args[0] != EWOULDBLOCK or self.timeout == 0.0:
raise
sys.exc_clear()
try:
self._wait(self._read_event)
except error, ex:
if ex[0] == EBADF:
except error:
ex = sys.exc_info()[1]
if ex.args[0] == EBADF:
return 0
raise
......@@ -453,20 +460,23 @@ class socket(object):
timeout = self.timeout
try:
return sock.send(data, flags)
except error, ex:
if ex[0] != EWOULDBLOCK or timeout == 0.0:
except error:
ex = sys.exc_info()[1]
if ex.args[0] != EWOULDBLOCK or timeout == 0.0:
raise
sys.exc_clear()
try:
self._wait(self._write_event)
except error, ex:
if ex[0] == EBADF:
except error:
ex = sys.exc_info()[1]
if ex.args[0] == EBADF:
return 0
raise
try:
return sock.send(data, flags)
except error, ex2:
if ex2[0] == EWOULDBLOCK:
except error:
ex2 = sys.exc_info()[1]
if ex2.args[0] == EWOULDBLOCK:
return 0
raise
......@@ -495,15 +505,17 @@ class socket(object):
sock = self._sock
try:
return sock.sendto(*args)
except error, ex:
if ex[0] != EWOULDBLOCK or timeout == 0.0:
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:
if ex2[0] == EWOULDBLOCK:
except error:
ex2 = sys.exc_info()[1]
if ex2.args[0] == EWOULDBLOCK:
return 0
raise
......@@ -546,7 +558,7 @@ class socket(object):
_s = ("def %s(self, *args): return self._sock.%s(*args)\n\n"
"%s.__doc__ = _realsocket.%s.__doc__\n")
for _m in set(__socket__._socketmethods) - set(locals()):
exec _s % (_m, _m, _m, _m)
exec (_s % (_m, _m, _m, _m))
del _m, _s
SocketType = socket
......@@ -616,8 +628,8 @@ def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT, source_address=N
sock.bind(source_address)
sock.connect(sa)
return sock
except error, ex:
err = ex
except error:
err = sys.exc_info()[1]
sys.exc_clear()
if sock is not None:
sock.close()
......
......@@ -22,6 +22,7 @@ import sys
import errno
from gevent.socket import socket, _fileobject, timeout_default
from gevent.socket import error as socket_error, EBADF
from gevent.hub import basestring
__implements__ = ['SSLSocket',
'wrap_socket',
......@@ -105,7 +106,8 @@ class SSLSocket(socket):
while True:
try:
return self._sslobj.read(len)
except SSLError, ex:
except SSLError:
ex = sys.exc_info()[1]
if ex.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
return ''
elif ex.args[0] == SSL_ERROR_WANT_READ:
......@@ -114,8 +116,9 @@ class SSLSocket(socket):
sys.exc_clear()
try:
self._wait(self._read_event, timeout_exc=_SSLErrorReadTimeout)
except socket_error, ex:
if ex[0] == EBADF:
except socket_error:
ex = sys.exc_info()[1]
if ex.args[0] == EBADF:
return ''
raise
elif ex.args[0] == SSL_ERROR_WANT_WRITE:
......@@ -125,8 +128,9 @@ class SSLSocket(socket):
try:
# note: using _SSLErrorReadTimeout rather than _SSLErrorWriteTimeout below is intentional
self._wait(self._write_event, timeout_exc=_SSLErrorReadTimeout)
except socket_error, ex:
if ex[0] == EBADF:
except socket_error:
ex = sys.exc_info()[1]
if ex.args[0] == EBADF:
return ''
raise
else:
......@@ -138,15 +142,17 @@ class SSLSocket(socket):
while True:
try:
return self._sslobj.write(data)
except SSLError, ex:
except SSLError:
ex = sys.exc_info()[1]
if ex.args[0] == SSL_ERROR_WANT_READ:
if self.timeout == 0.0:
raise
sys.exc_clear()
try:
self._wait(self._read_event, timeout_exc=_SSLErrorWriteTimeout)
except socket_error, ex:
if ex[0] == EBADF:
except socket_error:
ex = sys.exc_info()[1]
if ex.args[0] == EBADF:
return 0
raise
elif ex.args[0] == SSL_ERROR_WANT_WRITE:
......@@ -155,8 +161,9 @@ class SSLSocket(socket):
sys.exc_clear()
try:
self._wait(self._write_event, timeout_exc=_SSLErrorWriteTimeout)
except socket_error, ex:
if ex[0] == EBADF:
except socket_error:
ex = sys.exc_info()[1]
if ex.args[0] == EBADF:
return 0
raise
else:
......@@ -186,15 +193,17 @@ class SSLSocket(socket):
while True:
try:
v = self._sslobj.write(data)
except SSLError, x:
except SSLError:
x = sys.exc_info()[1]
if x.args[0] == SSL_ERROR_WANT_READ:
if self.timeout == 0.0:
return 0
sys.exc_clear()
try:
self._wait(self._read_event)
except socket_error, ex:
if ex[0] == EBADF:
except socket_error:
ex = sys.exc_info()[1]
if ex.args[0] == EBADF:
return 0
raise
elif x.args[0] == SSL_ERROR_WANT_WRITE:
......@@ -203,8 +212,9 @@ class SSLSocket(socket):
sys.exc_clear()
try:
self._wait(self._write_event)
except socket_error, ex:
if ex[0] == EBADF:
except socket_error:
ex = sys.exc_info()[1]
if ex.args[0] == EBADF:
return 0
raise
else:
......@@ -249,15 +259,17 @@ class SSLSocket(socket):
v = len(tmp_buffer)
buffer[:v] = tmp_buffer
return v
except SSLError, x:
except SSLError:
x = sys.exc_info()[1]
if x.args[0] == SSL_ERROR_WANT_READ:
sys.exc_clear()
if self.timeout == 0.0:
raise
try:
self._wait(self._read_event)
except socket_error, ex:
if ex[0] == EBADF:
except socket_error:
ex = sys.exc_info()[1]
if ex.args[0] == EBADF:
return 0
raise
continue
......@@ -290,7 +302,8 @@ class SSLSocket(socket):
while True:
try:
return self._sslobj.shutdown()
except SSLError, ex:
except SSLError:
ex = sys.exc_info()[1]
if ex.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
return ''
elif ex.args[0] == SSL_ERROR_WANT_READ:
......@@ -299,8 +312,9 @@ class SSLSocket(socket):
sys.exc_clear()
try:
self._wait(self._read_event, timeout_exc=_SSLErrorReadTimeout)
except socket_error, ex:
if ex[0] == EBADF:
except socket_error:
ex = sys.exc_info()[1]
if ex.args[0] == EBADF:
return ''
raise
elif ex.args[0] == SSL_ERROR_WANT_WRITE:
......@@ -309,8 +323,9 @@ class SSLSocket(socket):
sys.exc_clear()
try:
self._wait(self._write_event, timeout_exc=_SSLErrorWriteTimeout)
except socket_error, ex:
if ex[0] == EBADF:
except socket_error:
ex = sys.exc_info()[1]
if ex.args[0] == EBADF:
return ''
raise
else:
......@@ -340,7 +355,8 @@ class SSLSocket(socket):
while True:
try:
return self._sslobj.do_handshake()
except SSLError, ex:
except SSLError:
ex = sys.exc_info()[1]
if ex.args[0] == SSL_ERROR_WANT_READ:
if self.timeout == 0.0:
raise
......
......@@ -13,7 +13,8 @@ to arbitrary code.
which no switches occur, :class:`Timeout` is powerless.
"""
from gevent.hub import getcurrent, _NONE, get_hub
import sys
from gevent.hub import getcurrent, _NONE, get_hub, basestring
__all__ = ['Timeout',
'with_timeout']
......@@ -190,8 +191,8 @@ def with_timeout(seconds, function, *args, **kwds):
try:
try:
return function(*args, **kwds)
except Timeout, ex:
if ex is timeout and timeout_value is not _NONE:
except Timeout:
if sys.exc_info()[1] is timeout and timeout_value is not _NONE:
return timeout_value
raise
finally:
......
# Copyright (c) 2009 Denis Bilenko. See LICENSE for details.
__all__ = ['wrap_errors']
import sys
class wrap_errors(object):
"""Helper to make function return an exception, rather than raise it.
......@@ -35,8 +37,8 @@ class wrap_errors(object):
func = self.func
try:
return func(*args, **kwargs)
except self.errors, ex:
return ex
except self.errors:
return sys.exc_info()[1]
def __str__(self):
return str(self.func)
......
# Copyright (c) 2009-2010 Denis Bilenko. See LICENSE for details.
import sys
import traceback
from urllib import unquote
try:
from urllib import unquote
except ImportError:
from urllib.parse import unquote
from datetime import datetime
socket = __import__('socket')
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment