Commit 596043df authored by Denis Bilenko's avatar Denis Bilenko

replace "ex = sys.exc_info()[1]" with "as ex" #38

parent 8707190c
...@@ -10,7 +10,6 @@ variable. To enable threading resolver: ...@@ -10,7 +10,6 @@ variable. To enable threading resolver:
GEVENT_RESOLVER=thread python dns_mass_resolve.py GEVENT_RESOLVER=thread python dns_mass_resolve.py
""" """
from __future__ import with_statement from __future__ import with_statement
import sys
import gevent import gevent
from gevent import socket from gevent import socket
from gevent.pool import Pool from gevent.pool import Pool
...@@ -27,8 +26,7 @@ def job(url): ...@@ -27,8 +26,7 @@ def job(url):
try: try:
ip = socket.gethostbyname(url) ip = socket.gethostbyname(url)
print ('%s = %s' % (url, ip)) print ('%s = %s' % (url, ip))
except socket.gaierror: except socket.gaierror as ex:
ex = sys.exc_info()[1]
print ('%s failed with %s' % (url, ex)) print ('%s failed with %s' % (url, ex))
finally: finally:
finished += 1 finished += 1
......
...@@ -2,7 +2,6 @@ ...@@ -2,7 +2,6 @@
[1] http://pypi.python.org/pypi/py-sendfile/ [1] http://pypi.python.org/pypi/py-sendfile/
""" """
from sys import exc_info
from errno import EAGAIN from errno import EAGAIN
from sendfile import sendfile as original_sendfile from sendfile import sendfile as original_sendfile
from gevent.socket import wait_write from gevent.socket import wait_write
...@@ -15,8 +14,7 @@ def gevent_sendfile(out_fd, in_fd, offset, count): ...@@ -15,8 +14,7 @@ def gevent_sendfile(out_fd, in_fd, offset, count):
_offset, sent = original_sendfile(out_fd, in_fd, offset + total_sent, count - total_sent) _offset, sent = original_sendfile(out_fd, in_fd, offset + total_sent, count - total_sent)
#print '%s: sent %s [%d%%]' % (out_fd, sent, 100*total_sent/count) #print '%s: sent %s [%d%%]' % (out_fd, sent, 100*total_sent/count)
total_sent += sent total_sent += sent
except OSError: except OSError as ex:
ex = exc_info()[1]
if ex[0] == EAGAIN: if ex[0] == EAGAIN:
wait_write(out_fd) wait_write(out_fd)
else: else:
......
...@@ -51,14 +51,13 @@ def proxy(path, start_response, proxy_url): ...@@ -51,14 +51,13 @@ def proxy(path, start_response, proxy_url):
try: try:
try: try:
response = urllib2.urlopen(path) response = urllib2.urlopen(path)
except urllib2.HTTPError: except urllib2.HTTPError as ex:
response = sys.exc_info()[1] response = ex
print ('%s: %s %s' % (path, response.code, response.msg)) print ('%s: %s %s' % (path, response.code, response.msg))
headers = [(k, v) for (k, v) in response.headers.items() if k not in drop_headers] headers = [(k, v) for (k, v) in response.headers.items() if k not in drop_headers]
scheme, netloc, path, params, query, fragment = urlparse(path) scheme, netloc, path, params, query, fragment = urlparse(path)
host = (scheme or 'http') + '://' + netloc host = (scheme or 'http') + '://' + netloc
except Exception: except Exception as ex:
ex = sys.exc_info()[1]
sys.stderr.write('error while reading %s:\n' % path) sys.stderr.write('error while reading %s:\n' % path)
traceback.print_exc() traceback.print_exc()
tb = traceback.format_exc() tb = traceback.format_exc()
......
...@@ -179,8 +179,7 @@ class BaseServer(object): ...@@ -179,8 +179,7 @@ class BaseServer(object):
if hasattr(self, 'socket'): if hasattr(self, 'socket'):
try: try:
fileno = self.socket.fileno() fileno = self.socket.fileno()
except Exception: except Exception as ex:
ex = sys.exc_info()[1]
fileno = str(ex) fileno = str(ex)
result = 'fileno=%s ' % fileno result = 'fileno=%s ' % fileno
else: else:
...@@ -190,8 +189,7 @@ class BaseServer(object): ...@@ -190,8 +189,7 @@ class BaseServer(object):
result += 'address=%s:%s' % self.address result += 'address=%s:%s' % self.address
else: else:
result += 'address=%s' % (self.address, ) result += 'address=%s' % (self.address, )
except Exception: except Exception as ex:
ex = sys.exc_info()[1]
result += str(ex) or '<error>' result += str(ex) or '<error>'
try: try:
handle = getfuncname(self.__dict__['handle']) handle = getfuncname(self.__dict__['handle'])
...@@ -319,5 +317,5 @@ def _parse_address(address): ...@@ -319,5 +317,5 @@ def _parse_address(address):
def parse_address(address): def parse_address(address):
try: try:
return _parse_address(address) return _parse_address(address)
except ValueError: except ValueError as ex:
raise ValueError('Failed to parse address %r: %s' % (address, sys.exc_info()[1])) raise ValueError('Failed to parse address %r: %s' % (address, ex))
...@@ -76,8 +76,7 @@ class Event(object): ...@@ -76,8 +76,7 @@ class Event(object):
try: try:
result = self.hub.switch() result = self.hub.switch()
assert result is self, 'Invalid switch into Event.wait(): %r' % (result, ) assert result is self, 'Invalid switch into Event.wait(): %r' % (result, )
except Timeout: except Timeout as ex:
ex = sys.exc_info()[1]
if ex is not timer: if ex is not timer:
raise raise
finally: finally:
...@@ -268,8 +267,7 @@ class AsyncResult(object): ...@@ -268,8 +267,7 @@ class AsyncResult(object):
assert result is self, 'Invalid switch into AsyncResult.wait(): %r' % (result, ) assert result is self, 'Invalid switch into AsyncResult.wait(): %r' % (result, )
finally: finally:
timer.cancel() timer.cancel()
except Timeout: except Timeout as exc:
exc = sys.exc_info()[1]
self.unlink(switch) self.unlink(switch)
if exc is not timer: if exc is not timer:
raise raise
......
...@@ -101,8 +101,8 @@ else: ...@@ -101,8 +101,8 @@ else:
while True: while True:
try: try:
bytes_written += _write(fileno, _get_memory(data, bytes_written)) bytes_written += _write(fileno, _get_memory(data, bytes_written))
except (IOError, OSError): except (IOError, OSError) as ex:
code = sys.exc_info()[1].args[0] code = ex.args[0]
if code not in ignored_errors: if code not in ignored_errors:
raise raise
sys.exc_clear() sys.exc_clear()
...@@ -114,8 +114,8 @@ else: ...@@ -114,8 +114,8 @@ else:
while True: while True:
try: try:
data = _read(self.fileno(), size) data = _read(self.fileno(), size)
except (IOError, OSError): except (IOError, OSError) as ex:
code = sys.exc_info()[1].args[0] code = ex.args[0]
if code not in ignored_errors: if code not in ignored_errors:
raise raise
sys.exc_clear() sys.exc_clear()
......
...@@ -291,9 +291,9 @@ class Greenlet(greenlet): ...@@ -291,9 +291,9 @@ class Greenlet(greenlet):
assert result is self, 'Invalid switch into Greenlet.join(): %r' % (result, ) assert result is self, 'Invalid switch into Greenlet.join(): %r' % (result, )
finally: finally:
t.cancel() t.cancel()
except Timeout: except Timeout as ex:
self.unlink(switch) self.unlink(switch)
if sys.exc_info()[1] is not t: if ex is not t:
raise raise
except: except:
self.unlink(switch) self.unlink(switch)
......
...@@ -9,7 +9,6 @@ concurrency: its :meth:`spawn <Pool.spawn>` method blocks if the number of ...@@ -9,7 +9,6 @@ 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. greenlets in the pool has already reached the limit, until there is a free slot.
""" """
import sys
from bisect import insort_right from bisect import insort_right
from gevent.hub import GreenletExit, getcurrent, kill as _kill, PY3 from gevent.hub import GreenletExit, getcurrent, kill as _kill, PY3
...@@ -116,8 +115,7 @@ class Group(object): ...@@ -116,8 +115,7 @@ class Group(object):
if not block: if not block:
break break
joinall(self.greenlets) joinall(self.greenlets)
except Timeout: except Timeout as ex:
ex = sys.exc_info()[1]
if ex is not timer: if ex is not timer:
raise raise
finally: finally:
......
...@@ -308,8 +308,7 @@ class WSGIHandler(object): ...@@ -308,8 +308,7 @@ class WSGIHandler(object):
# for compatibility with older versions of pywsgi, we pass self.requestline as an argument there # for compatibility with older versions of pywsgi, we pass self.requestline as an argument there
if not self.read_request(self.requestline): if not self.read_request(self.requestline):
return ('400', _BAD_REQUEST_RESPONSE) return ('400', _BAD_REQUEST_RESPONSE)
except Exception: except Exception as ex:
ex = sys.exc_info()[1]
if not isinstance(ex, ValueError): if not isinstance(ex, ValueError):
traceback.print_exc() traceback.print_exc()
self.log_error('Invalid request: %s', str(ex) or ex.__class__.__name__) self.log_error('Invalid request: %s', str(ex) or ex.__class__.__name__)
...@@ -319,8 +318,7 @@ class WSGIHandler(object): ...@@ -319,8 +318,7 @@ class WSGIHandler(object):
self.application = self.server.application self.application = self.server.application
try: try:
self.handle_one_response() self.handle_one_response()
except socket.error: except socket.error as ex:
ex = sys.exc_info()[1]
# Broken pipe, connection reset by peer # Broken pipe, connection reset by peer
if ex.args[0] in (errno.EPIPE, errno.ECONNRESET): if ex.args[0] in (errno.EPIPE, errno.ECONNRESET):
sys.exc_clear() sys.exc_clear()
......
# Copyright (c) 2011 Denis Bilenko. See LICENSE for details. # Copyright (c) 2011 Denis Bilenko. See LICENSE for details.
from __future__ import absolute_import from __future__ import absolute_import
import os import os
import sys
from _socket import getservbyname, getaddrinfo, gaierror, error from _socket import getservbyname, getaddrinfo, gaierror, error
from gevent.hub import Waiter, get_hub, string_types from gevent.hub import Waiter, get_hub, string_types
from gevent.socket import AF_UNSPEC, AF_INET, AF_INET6, SOCK_STREAM, SOCK_DGRAM, SOCK_RAW, AI_NUMERICHOST, EAI_SERVICE, AI_PASSIVE from gevent.socket import AF_UNSPEC, AF_INET, AF_INET6, SOCK_STREAM, SOCK_DGRAM, SOCK_RAW, AI_NUMERICHOST, EAI_SERVICE, AI_PASSIVE
...@@ -99,8 +98,7 @@ class Resolver(object): ...@@ -99,8 +98,7 @@ class Resolver(object):
port = getservbyname(port, 'udp') port = getservbyname(port, 'udp')
else: else:
raise gaierror(EAI_SERVICE, 'Servname not supported for ai_socktype') raise gaierror(EAI_SERVICE, 'Servname not supported for ai_socktype')
except error: except error as ex:
ex = sys.exc_info()[1]
if 'not found' in str(ex): if 'not found' in str(ex):
raise gaierror(EAI_SERVICE, 'Servname not supported for ai_socktype') raise gaierror(EAI_SERVICE, 'Servname not supported for ai_socktype')
else: else:
......
# Copyright (c) 2009-2011 Denis Bilenko. See LICENSE for details. # Copyright (c) 2009-2011 Denis Bilenko. See LICENSE for details.
from __future__ import absolute_import from __future__ import absolute_import
import sys
from gevent.timeout import Timeout from gevent.timeout import Timeout
from gevent.event import Event from gevent.event import Event
from gevent.hub import get_hub from gevent.hub import get_hub
...@@ -63,8 +62,7 @@ def select(rlist, wlist, xlist, timeout=None): ...@@ -63,8 +62,7 @@ def select(rlist, wlist, xlist, timeout=None):
watcher.priority = MAXPRI watcher.priority = MAXPRI
watcher.start(result.add_write, writefd) watcher.start(result.add_write, writefd)
watchers.append(watcher) watchers.append(watcher)
except IOError: except IOError as ex:
ex = sys.exc_info()[1]
raise error(*ex.args) raise error(*ex.args)
result.event.wait(timeout=timeout) result.event.wait(timeout=timeout)
return result.read, result.write, [] return result.read, result.write, []
......
...@@ -151,8 +151,7 @@ def _tcp_listener(address, backlog=50, reuse_addr=None, family=_socket.AF_INET): ...@@ -151,8 +151,7 @@ def _tcp_listener(address, backlog=50, reuse_addr=None, family=_socket.AF_INET):
sock.setsockopt(_socket.SOL_SOCKET, _socket.SO_REUSEADDR, reuse_addr) sock.setsockopt(_socket.SOL_SOCKET, _socket.SO_REUSEADDR, reuse_addr)
try: try:
sock.bind(address) sock.bind(address)
except _socket.error: except _socket.error as ex:
ex = sys.exc_info()[1]
strerror = getattr(ex, 'strerror', None) strerror = getattr(ex, 'strerror', None)
if strerror is not None: if strerror is not None:
ex.strerror = strerror + ': ' + repr(address) ex.strerror = strerror + ': ' + repr(address)
...@@ -169,8 +168,7 @@ def _udp_socket(address, backlog=50, reuse_addr=None, family=_socket.AF_INET): ...@@ -169,8 +168,7 @@ def _udp_socket(address, backlog=50, reuse_addr=None, family=_socket.AF_INET):
sock.setsockopt(_socket.SOL_SOCKET, _socket.SO_REUSEADDR, reuse_addr) sock.setsockopt(_socket.SOL_SOCKET, _socket.SO_REUSEADDR, reuse_addr)
try: try:
sock.bind(address) sock.bind(address)
except _socket.error: except _socket.error as ex:
ex = sys.exc_info()[1]
strerror = getattr(ex, 'strerror', None) strerror = getattr(ex, 'strerror', None)
if strerror is not None: if strerror is not None:
ex.strerror = strerror + ': ' + repr(address) ex.strerror = strerror + ': ' + repr(address)
......
...@@ -247,8 +247,8 @@ class socket(object): ...@@ -247,8 +247,8 @@ class socket(object):
def _formatinfo(self): def _formatinfo(self):
try: try:
fileno = self.fileno() fileno = self.fileno()
except Exception: except Exception as ex:
fileno = str(sys.exc_info()[1]) fileno = str(ex)
try: try:
sockname = self.getsockname() sockname = self.getsockname()
sockname = '%s:%s' % sockname sockname = '%s:%s' % sockname
...@@ -302,8 +302,7 @@ class socket(object): ...@@ -302,8 +302,7 @@ class socket(object):
try: try:
client_socket, address = sock.accept() client_socket, address = sock.accept()
break break
except error: except error as ex:
ex = sys.exc_info()[1]
if ex[0] != EWOULDBLOCK or self.timeout == 0.0: if ex[0] != EWOULDBLOCK or self.timeout == 0.0:
raise raise
sys.exc_clear() sys.exc_clear()
...@@ -352,8 +351,7 @@ class socket(object): ...@@ -352,8 +351,7 @@ class socket(object):
return self.connect(address) or 0 return self.connect(address) or 0
except timeout: except timeout:
return EAGAIN return EAGAIN
except error: except error as ex:
ex = sys.exc_info()[1]
if type(ex) is error: if type(ex) is error:
return ex.args[0] return ex.args[0]
else: else:
...@@ -379,8 +377,7 @@ class socket(object): ...@@ -379,8 +377,7 @@ class socket(object):
while True: while True:
try: try:
return sock.recv(*args) return sock.recv(*args)
except error: except error as ex:
ex = sys.exc_info()[1]
if ex.args[0] != EWOULDBLOCK or self.timeout == 0.0: if ex.args[0] != EWOULDBLOCK or self.timeout == 0.0:
raise raise
# QQQ without clearing exc_info test__refcount.test_clean_exit fails # QQQ without clearing exc_info test__refcount.test_clean_exit fails
...@@ -392,8 +389,7 @@ class socket(object): ...@@ -392,8 +389,7 @@ class socket(object):
while True: while True:
try: try:
return sock.recvfrom(*args) return sock.recvfrom(*args)
except error: except error as ex:
ex = sys.exc_info()[1]
if ex.args[0] != EWOULDBLOCK or self.timeout == 0.0: if ex.args[0] != EWOULDBLOCK or self.timeout == 0.0:
raise raise
sys.exc_clear() sys.exc_clear()
...@@ -404,8 +400,7 @@ class socket(object): ...@@ -404,8 +400,7 @@ class socket(object):
while True: while True:
try: try:
return sock.recvfrom_into(*args) return sock.recvfrom_into(*args)
except error: except error as ex:
ex = sys.exc_info()[1]
if ex.args[0] != EWOULDBLOCK or self.timeout == 0.0: if ex.args[0] != EWOULDBLOCK or self.timeout == 0.0:
raise raise
sys.exc_clear() sys.exc_clear()
...@@ -416,8 +411,7 @@ class socket(object): ...@@ -416,8 +411,7 @@ class socket(object):
while True: while True:
try: try:
return sock.recv_into(*args) return sock.recv_into(*args)
except error: except error as ex:
ex = sys.exc_info()[1]
if ex.args[0] != EWOULDBLOCK or self.timeout == 0.0: if ex.args[0] != EWOULDBLOCK or self.timeout == 0.0:
raise raise
sys.exc_clear() sys.exc_clear()
...@@ -429,16 +423,14 @@ class socket(object): ...@@ -429,16 +423,14 @@ class socket(object):
timeout = self.timeout timeout = self.timeout
try: try:
return sock.send(data, flags) return sock.send(data, flags)
except error: except error as ex:
ex = sys.exc_info()[1]
if ex.args[0] != EWOULDBLOCK or timeout == 0.0: if ex.args[0] != EWOULDBLOCK or timeout == 0.0:
raise raise
sys.exc_clear() sys.exc_clear()
self._wait(self._write_event) self._wait(self._write_event)
try: try:
return sock.send(data, flags) return sock.send(data, flags)
except error: except error as ex2:
ex2 = sys.exc_info()[1]
if ex2.args[0] == EWOULDBLOCK: if ex2.args[0] == EWOULDBLOCK:
return 0 return 0
raise raise
...@@ -468,16 +460,14 @@ class socket(object): ...@@ -468,16 +460,14 @@ class socket(object):
sock = self._sock sock = self._sock
try: try:
return sock.sendto(*args) return sock.sendto(*args)
except error: except error as ex:
ex = sys.exc_info()[1]
if ex.args[0] != EWOULDBLOCK or timeout == 0.0: if ex.args[0] != EWOULDBLOCK or timeout == 0.0:
raise raise
sys.exc_clear() sys.exc_clear()
self._wait(self._write_event) self._wait(self._write_event)
try: try:
return sock.sendto(*args) return sock.sendto(*args)
except error: except error as ex2:
ex2 = sys.exc_info()[1]
if ex2.args[0] == EWOULDBLOCK: if ex2.args[0] == EWOULDBLOCK:
return 0 return 0
raise raise
...@@ -574,8 +564,7 @@ def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT, source_address=N ...@@ -574,8 +564,7 @@ def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT, source_address=N
sock.bind(source_address) sock.bind(source_address)
sock.connect(sa) sock.connect(sa)
return sock return sock
except error: except error as err:
err = sys.exc_info()[1]
# without exc_clear(), if connect() fails once, the socket is referenced by the frame in exc_info # without exc_clear(), if connect() fails once, the socket is referenced by the frame in exc_info
# and the next bind() fails (see test__socket.TestCreateConnection) # and the next bind() fails (see test__socket.TestCreateConnection)
# that does not happen with regular sockets though, because _socket.socket.connect() is a built-in. # that does not happen with regular sockets though, because _socket.socket.connect() is a built-in.
......
...@@ -104,8 +104,7 @@ class SSLSocket(socket): ...@@ -104,8 +104,7 @@ class SSLSocket(socket):
while True: while True:
try: try:
return self._sslobj.read(len) return self._sslobj.read(len)
except SSLError: except SSLError as ex:
ex = sys.exc_info()[1]
if ex.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs: if ex.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
return '' return ''
elif ex.args[0] == SSL_ERROR_WANT_READ: elif ex.args[0] == SSL_ERROR_WANT_READ:
...@@ -128,8 +127,7 @@ class SSLSocket(socket): ...@@ -128,8 +127,7 @@ class SSLSocket(socket):
while True: while True:
try: try:
return self._sslobj.write(data) return self._sslobj.write(data)
except SSLError: except SSLError as ex:
ex = sys.exc_info()[1]
if ex.args[0] == SSL_ERROR_WANT_READ: if ex.args[0] == SSL_ERROR_WANT_READ:
if self.timeout == 0.0: if self.timeout == 0.0:
raise raise
...@@ -167,8 +165,7 @@ class SSLSocket(socket): ...@@ -167,8 +165,7 @@ class SSLSocket(socket):
while True: while True:
try: try:
v = self._sslobj.write(data) v = self._sslobj.write(data)
except SSLError: except SSLError as x:
x = sys.exc_info()[1]
if x.args[0] == SSL_ERROR_WANT_READ: if x.args[0] == SSL_ERROR_WANT_READ:
if self.timeout == 0.0: if self.timeout == 0.0:
return 0 return 0
...@@ -221,8 +218,7 @@ class SSLSocket(socket): ...@@ -221,8 +218,7 @@ class SSLSocket(socket):
v = len(tmp_buffer) v = len(tmp_buffer)
buffer[:v] = tmp_buffer buffer[:v] = tmp_buffer
return v return v
except SSLError: except SSLError as x:
x = sys.exc_info()[1]
if x.args[0] == SSL_ERROR_WANT_READ: if x.args[0] == SSL_ERROR_WANT_READ:
if self.timeout == 0.0: if self.timeout == 0.0:
raise raise
...@@ -258,8 +254,7 @@ class SSLSocket(socket): ...@@ -258,8 +254,7 @@ class SSLSocket(socket):
while True: while True:
try: try:
return self._sslobj.shutdown() return self._sslobj.shutdown()
except SSLError: except SSLError as ex:
ex = sys.exc_info()[1]
if ex.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs: if ex.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
return '' return ''
elif ex.args[0] == SSL_ERROR_WANT_READ: elif ex.args[0] == SSL_ERROR_WANT_READ:
...@@ -299,8 +294,7 @@ class SSLSocket(socket): ...@@ -299,8 +294,7 @@ class SSLSocket(socket):
while True: while True:
try: try:
return self._sslobj.do_handshake() return self._sslobj.do_handshake()
except SSLError: except SSLError as ex:
ex = sys.exc_info()[1]
if ex.args[0] == SSL_ERROR_WANT_READ: if ex.args[0] == SSL_ERROR_WANT_READ:
if self.timeout == 0.0: if self.timeout == 0.0:
raise raise
......
...@@ -325,5 +325,5 @@ class ThreadResult(object): ...@@ -325,5 +325,5 @@ class ThreadResult(object):
def wrap_errors(errors, function, args, kwargs): def wrap_errors(errors, function, args, kwargs):
try: try:
return True, function(*args, **kwargs) return True, function(*args, **kwargs)
except errors: except errors as ex:
return False, sys.exc_info()[1] return False, ex
...@@ -13,7 +13,6 @@ to arbitrary code. ...@@ -13,7 +13,6 @@ to arbitrary code.
which no switches occur, :class:`Timeout` is powerless. which no switches occur, :class:`Timeout` is powerless.
""" """
import sys
from gevent.hub import getcurrent, _NONE, get_hub, string_types from gevent.hub import getcurrent, _NONE, get_hub, string_types
__all__ = ['Timeout', __all__ = ['Timeout',
...@@ -175,8 +174,8 @@ def with_timeout(seconds, function, *args, **kwds): ...@@ -175,8 +174,8 @@ def with_timeout(seconds, function, *args, **kwds):
try: try:
try: try:
return function(*args, **kwds) return function(*args, **kwds)
except Timeout: except Timeout as ex:
if sys.exc_info()[1] is timeout and timeout_value is not _NONE: if ex is timeout and timeout_value is not _NONE:
return timeout_value return timeout_value
raise raise
finally: finally:
......
# Copyright (c) 2009 Denis Bilenko. See LICENSE for details. # Copyright (c) 2009 Denis Bilenko. See LICENSE for details.
__all__ = ['wrap_errors'] __all__ = ['wrap_errors']
import sys
class wrap_errors(object): class wrap_errors(object):
"""Helper to make function return an exception, rather than raise it. """Helper to make function return an exception, rather than raise it.
...@@ -37,8 +35,8 @@ class wrap_errors(object): ...@@ -37,8 +35,8 @@ class wrap_errors(object):
func = self.func func = self.func
try: try:
return func(*args, **kwargs) return func(*args, **kwargs)
except self.errors: except self.errors as ex:
return sys.exc_info()[1] return ex
def __str__(self): def __str__(self):
return str(self.func) return str(self.func)
......
...@@ -296,8 +296,7 @@ def test_outer_timeout_is_not_lost(self): ...@@ -296,8 +296,7 @@ def test_outer_timeout_is_not_lost(self):
try: try:
try: try:
result = self.wait(timeout=1) result = self.wait(timeout=1)
except gevent.Timeout: except gevent.Timeout as ex:
ex = sys.exc_info()[1]
assert ex is timeout, (ex, timeout) assert ex is timeout, (ex, timeout)
else: else:
raise AssertionError('must raise Timeout (returned %r)' % (result, )) raise AssertionError('must raise Timeout (returned %r)' % (result, ))
...@@ -346,8 +345,7 @@ class GenericGetTestCase(TestCase): ...@@ -346,8 +345,7 @@ class GenericGetTestCase(TestCase):
timeout = gevent.Timeout(0.01) timeout = gevent.Timeout(0.01)
try: try:
self.wait(timeout=timeout) self.wait(timeout=timeout)
except gevent.Timeout: except gevent.Timeout as ex:
ex = sys.exc_info()[1]
assert ex is timeout, (ex, timeout) assert ex is timeout, (ex, timeout)
delay = time.time() - start delay = time.time() - start
assert 0.01 - 0.001 <= delay < 0.01 + 0.01 + 0.1, delay assert 0.01 - 0.001 <= delay < 0.01 + 0.01 + 0.1, delay
...@@ -359,8 +357,7 @@ class GenericGetTestCase(TestCase): ...@@ -359,8 +357,7 @@ class GenericGetTestCase(TestCase):
timeout = gevent.Timeout(0.01, exception=error) timeout = gevent.Timeout(0.01, exception=error)
try: try:
self.wait(timeout=timeout) self.wait(timeout=timeout)
except RuntimeError: except RuntimeError as ex:
ex = sys.exc_info()[1]
assert ex is error, (ex, error) assert ex is error, (ex, error)
delay = time.time() - start delay = time.time() - start
assert 0.01 - 0.001 <= delay < 0.01 + 0.01 + 0.1, delay assert 0.01 - 0.001 <= delay < 0.01 + 0.01 + 0.1, delay
......
...@@ -49,8 +49,7 @@ class Test(greentest.TestCase): ...@@ -49,8 +49,7 @@ class Test(greentest.TestCase):
try: try:
with Timeout(DELAY) as t: with Timeout(DELAY) as t:
sleep(DELAY * 2) sleep(DELAY * 2)
except Timeout: except Timeout as ex:
ex = sys.exc_info()[1]
assert ex is t, (ex, t) assert ex is t, (ex, t)
else: else:
raise AssertionError('must raise Timeout') raise AssertionError('must raise Timeout')
...@@ -59,8 +58,7 @@ class Test(greentest.TestCase): ...@@ -59,8 +58,7 @@ class Test(greentest.TestCase):
try: try:
with Timeout(DELAY, IOError("Operation takes way too long")): with Timeout(DELAY, IOError("Operation takes way too long")):
sleep(DELAY * 2) sleep(DELAY * 2)
except IOError: except IOError as ex:
ex = sys.exc_info()[1]
assert str(ex) == "Operation takes way too long", repr(ex) assert str(ex) == "Operation takes way too long", repr(ex)
# Providing classes instead of values should be possible too: # Providing classes instead of values should be possible too:
...@@ -119,8 +117,7 @@ class Test(greentest.TestCase): ...@@ -119,8 +117,7 @@ class Test(greentest.TestCase):
with Timeout(DELAY * 2) as t2: with Timeout(DELAY * 2) as t2:
try: try:
sleep(DELAY * 3) sleep(DELAY * 3)
except Timeout: except Timeout as ex:
ex = sys.exc_info()[1]
assert ex is t1, (ex, t1) assert ex is t1, (ex, t1)
assert not t1.pending, t1 assert not t1.pending, t1
assert t2.pending, t2 assert t2.pending, t2
...@@ -130,8 +127,7 @@ class Test(greentest.TestCase): ...@@ -130,8 +127,7 @@ class Test(greentest.TestCase):
with Timeout(DELAY) as t2: with Timeout(DELAY) as t2:
try: try:
sleep(DELAY * 3) sleep(DELAY * 3)
except Timeout: except Timeout as ex:
ex = sys.exc_info()[1]
assert ex is t2, (ex, t2) assert ex is t2, (ex, t2)
assert t1.pending, t1 assert t1.pending, t1
assert not t2.pending, t2 assert not t2.pending, t2
......
import greentest import greentest
import gevent import gevent
import sys
from gevent.event import Event, AsyncResult from gevent.event import Event, AsyncResult
DELAY = 0.01 DELAY = 0.01
...@@ -46,8 +45,7 @@ class TestAsyncResult(greentest.TestCase): ...@@ -46,8 +45,7 @@ class TestAsyncResult(greentest.TestCase):
try: try:
result = e.get() result = e.get()
log.append(('received', result)) log.append(('received', result))
except Exception: except Exception as ex:
ex = sys.exc_info()[1]
log.append(('catched', ex)) log.append(('catched', ex))
gevent.spawn(waiter) gevent.spawn(waiter)
obj = Exception() obj = Exception()
......
...@@ -284,8 +284,7 @@ class TestStuff(greentest.TestCase): ...@@ -284,8 +284,7 @@ class TestStuff(greentest.TestCase):
b = gevent.spawn(lambda: getcurrent().throw(ExpectedError('second'))) b = gevent.spawn(lambda: getcurrent().throw(ExpectedError('second')))
try: try:
gevent.joinall([a, b], raise_error=True) gevent.joinall([a, b], raise_error=True)
except ExpectedError: except ExpectedError as ex:
ex = sys.exc_info()[1]
assert 'second' in str(ex), repr(str(ex)) assert 'second' in str(ex), repr(str(ex))
gevent.joinall([a, b]) gevent.joinall([a, b])
......
...@@ -26,7 +26,6 @@ If either operation blocked the whole script would block and timeout. ...@@ -26,7 +26,6 @@ If either operation blocked the whole script would block and timeout.
import greentest import greentest
from gevent import monkey from gevent import monkey
monkey.patch_all() monkey.patch_all()
import sys
try: try:
import urllib2 import urllib2
except ImportError: except ImportError:
...@@ -56,8 +55,7 @@ class TestGreenness(greentest.TestCase): ...@@ -56,8 +55,7 @@ class TestGreenness(greentest.TestCase):
try: try:
urllib2.urlopen('http://127.0.0.1:%s' % port) urllib2.urlopen('http://127.0.0.1:%s' % port)
assert False, 'should not get there' assert False, 'should not get there'
except urllib2.HTTPError: except urllib2.HTTPError as ex:
ex = sys.exc_info()[1]
assert ex.code == 501, repr(ex) assert ex.code == 501, repr(ex)
server.get(0.01) server.get(0.01)
self.assertEqual(self.httpd.request_count, 1) self.assertEqual(self.httpd.request_count, 1)
......
...@@ -277,8 +277,7 @@ class CommonTests(TestCase): ...@@ -277,8 +277,7 @@ class CommonTests(TestCase):
fd.close() fd.close()
finally: finally:
timeout.cancel() timeout.cancel()
except AssertionError: except AssertionError as ex:
ex = sys.exc_info()[1]
if ex is not exception: if ex is not exception:
raise raise
...@@ -294,8 +293,7 @@ class CommonTests(TestCase): ...@@ -294,8 +293,7 @@ class CommonTests(TestCase):
try: try:
result = fd.readline() result = fd.readline()
assert not result, 'The remote side is expected to close the connection, but it send %r' % (result, ) assert not result, 'The remote side is expected to close the connection, but it send %r' % (result, )
except socket.error: except socket.error as ex:
ex = sys.exc_info()[1]
if ex.args[0] not in CONN_ABORTED_ERRORS: if ex.args[0] not in CONN_ABORTED_ERRORS:
raise raise
...@@ -952,8 +950,7 @@ class ChunkedInputTests(TestCase): ...@@ -952,8 +950,7 @@ class ChunkedInputTests(TestCase):
fd.write(req) fd.write(req)
try: try:
read_http(fd, body="pong") read_http(fd, body="pong")
except AssertionError: except AssertionError as ex:
ex = sys.exc_info()[1]
if str(ex).startswith('Unexpected code: 400'): if str(ex).startswith('Unexpected code: 400'):
if not server_implements_chunked: if not server_implements_chunked:
print 'ChunkedNotImplementedWarning' print 'ChunkedNotImplementedWarning'
...@@ -1005,8 +1002,7 @@ class Expect100ContinueTests(TestCase): ...@@ -1005,8 +1002,7 @@ class Expect100ContinueTests(TestCase):
fd.write('PUT / HTTP/1.1\r\nHost: localhost\r\nContent-length: 1025\r\nExpect: 100-continue\r\n\r\n') fd.write('PUT / HTTP/1.1\r\nHost: localhost\r\nContent-length: 1025\r\nExpect: 100-continue\r\n\r\n')
try: try:
read_http(fd, code=417, body="failure") read_http(fd, code=417, body="failure")
except AssertionError: except AssertionError as ex:
ex = sys.exc_info()[1]
if str(ex).startswith('Unexpected code: 400'): if str(ex).startswith('Unexpected code: 400'):
if not server_implements_100continue: if not server_implements_100continue:
print '100ContinueNotImplementedWarning' print '100ContinueNotImplementedWarning'
......
...@@ -3,7 +3,6 @@ from gevent import socket ...@@ -3,7 +3,6 @@ from gevent import socket
import gevent import gevent
from gevent.server import StreamServer from gevent.server import StreamServer
import errno import errno
import sys
import os import os
...@@ -52,8 +51,7 @@ class Settings: ...@@ -52,8 +51,7 @@ class Settings:
# attempt to send anything reset the connection # attempt to send anything reset the connection
try: try:
self.send_request() self.send_request()
except socket.error: except socket.error as ex:
ex = sys.exc_info()[1]
if ex.args[0] != errno.ECONNRESET: if ex.args[0] != errno.ECONNRESET:
raise raise
...@@ -94,8 +92,7 @@ class TestCase(greentest.TestCase): ...@@ -94,8 +92,7 @@ class TestCase(greentest.TestCase):
try: try:
conn = self.makefile() conn = self.makefile()
raise AssertionError('Connection was not refused: %r' % (conn._sock, )) raise AssertionError('Connection was not refused: %r' % (conn._sock, ))
except socket.error: except socket.error as ex:
ex = sys.exc_info()[1]
if ex.args[0] not in (errno.ECONNREFUSED, errno.EADDRNOTAVAIL): if ex.args[0] not in (errno.ECONNREFUSED, errno.EADDRNOTAVAIL):
raise raise
...@@ -259,8 +256,7 @@ class TestDefaultSpawn(TestCase): ...@@ -259,8 +256,7 @@ class TestDefaultSpawn(TestCase):
result = conn.read() result = conn.read()
if result: if result:
assert result.startswith('HTTP/1.0 500 Internal Server Error'), repr(result) assert result.startswith('HTTP/1.0 500 Internal Server Error'), repr(result)
except socket.error: except socket.error as ex:
ex = sys.exc_info()[1]
if ex.args[0] == 10053: if ex.args[0] == 10053:
pass # "established connection was aborted by the software in your host machine" pass # "established connection was aborted by the software in your host machine"
elif ex.args[0] == errno.ECONNRESET: elif ex.args[0] == errno.ECONNRESET:
......
import signal import signal
import greentest import greentest
import gevent import gevent
import sys
class Expected(Exception): class Expected(Exception):
...@@ -30,16 +29,14 @@ if hasattr(signal, 'SIGALRM'): ...@@ -30,16 +29,14 @@ if hasattr(signal, 'SIGALRM'):
try: try:
gevent.sleep(2) gevent.sleep(2)
raise AssertionError('must raise Expected') raise AssertionError('must raise Expected')
except Expected: except Expected as ex:
ex = sys.exc_info()[1]
assert str(ex) == 'TestSignal', ex assert str(ex) == 'TestSignal', ex
# also let's check that alarm is persistent # also let's check that alarm is persistent
signal.alarm(1) signal.alarm(1)
try: try:
gevent.sleep(2) gevent.sleep(2)
raise AssertionError('must raise Expected') raise AssertionError('must raise Expected')
except Expected: except Expected as ex:
ex = sys.exc_info()[1]
assert str(ex) == 'TestSignal', ex assert str(ex) == 'TestSignal', ex
finally: finally:
sig.cancel() sig.cancel()
......
...@@ -175,8 +175,7 @@ class TestCreateConnection(greentest.TestCase): ...@@ -175,8 +175,7 @@ class TestCreateConnection(greentest.TestCase):
def test(self): def test(self):
try: try:
socket.create_connection(('localhost', get_port()), timeout=30, source_address=('', get_port())) socket.create_connection(('localhost', get_port()), timeout=30, source_address=('', get_port()))
except socket.error: except socket.error as ex:
ex = sys.exc_info()[1]
if 'refused' not in str(ex).lower(): if 'refused' not in str(ex).lower():
raise raise
else: else:
......
#!/usr/bin/python #!/usr/bin/python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from __future__ import with_statement from __future__ import with_statement
import sys
import re import re
import greentest import greentest
import socket import socket
...@@ -29,8 +28,8 @@ def _run(function, *args): ...@@ -29,8 +28,8 @@ def _run(function, *args):
result = function(*args) result = function(*args)
assert not isinstance(result, BaseException), repr(result) assert not isinstance(result, BaseException), repr(result)
return result return result
except Exception: except Exception as ex:
return sys.exc_info()[1] return ex
def format_call(function, args): def format_call(function, args):
......
...@@ -19,7 +19,6 @@ ...@@ -19,7 +19,6 @@
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE. # THE SOFTWARE.
import sys
import greentest import greentest
from gevent.socket import socket, error from gevent.socket import socket, error
...@@ -37,8 +36,7 @@ class TestSocketErrors(greentest.TestCase): ...@@ -37,8 +36,7 @@ class TestSocketErrors(greentest.TestCase):
s = socket() s = socket()
try: try:
s.connect(('127.0.0.1', 81)) s.connect(('127.0.0.1', 81))
except error: except error as ex:
ex = sys.exc_info()[1]
assert ex.args[0] == ECONNREFUSED, repr(ex) assert ex.args[0] == ECONNREFUSED, repr(ex)
assert 'refused' in str(ex).lower(), str(ex) assert 'refused' in str(ex).lower(), str(ex)
......
import sys
import gevent import gevent
from gevent import socket from gevent import socket
import greentest import greentest
...@@ -29,8 +28,7 @@ class Test(greentest.TestCase): ...@@ -29,8 +28,7 @@ class Test(greentest.TestCase):
try: try:
result = sock.recv(1024) result = sock.recv(1024)
raise AssertionError('Expected timeout to be raised, instead recv() returned %r' % (result, )) raise AssertionError('Expected timeout to be raised, instead recv() returned %r' % (result, ))
except socket.error: except socket.error as ex:
ex = sys.exc_info()[1]
self.assertEqual(ex.args, ('timed out',)) self.assertEqual(ex.args, ('timed out',))
self.assertEqual(str(ex), 'timed out') self.assertEqual(str(ex), 'timed out')
self.assertEqual(ex[0], 'timed out') self.assertEqual(ex[0], 'timed out')
......
...@@ -131,8 +131,7 @@ class Test(greentest.TestCase): ...@@ -131,8 +131,7 @@ class Test(greentest.TestCase):
for i in range(7): for i in range(7):
try: try:
p1 = subprocess.Popen('this_name_must_not_exist') p1 = subprocess.Popen('this_name_must_not_exist')
except OSError: except OSError as ex:
ex = sys.exc_info()[1]
if ex.errno != errno.ENOENT: if ex.errno != errno.ENOENT:
raise raise
else: else:
......
...@@ -20,8 +20,7 @@ class Test(greentest.TestCase): ...@@ -20,8 +20,7 @@ class Test(greentest.TestCase):
try: try:
gevent.sleep(0.001) gevent.sleep(0.001)
except SystemExit: except SystemExit as ex:
ex = sys.exc_info()[1]
assert str(ex) == MSG, repr(str(ex)) assert str(ex) == MSG, repr(str(ex))
else: else:
raise AssertionError('must raise SystemExit') raise AssertionError('must raise SystemExit')
...@@ -41,8 +40,7 @@ class Test(greentest.TestCase): ...@@ -41,8 +40,7 @@ class Test(greentest.TestCase):
try: try:
gevent.sleep(0.001) gevent.sleep(0.001)
except SystemError: except SystemError as ex:
ex = sys.exc_info()[1]
assert str(ex) == MSG, repr(str(ex)) assert str(ex) == MSG, repr(str(ex))
else: else:
raise AssertionError('must raise SystemError') raise AssertionError('must raise SystemError')
......
import greentest import greentest
import gevent import gevent
import sys
from gevent.hub import get_hub from gevent.hub import get_hub
DELAY = 0.01 DELAY = 0.01
...@@ -12,16 +11,14 @@ class TestDirectRaise(greentest.TestCase): ...@@ -12,16 +11,14 @@ class TestDirectRaise(greentest.TestCase):
def test_direct_raise_class(self): def test_direct_raise_class(self):
try: try:
raise gevent.Timeout raise gevent.Timeout
except gevent.Timeout: except gevent.Timeout as t:
t = sys.exc_info()[1]
assert not t.pending, repr(t) assert not t.pending, repr(t)
def test_direct_raise_instance(self): def test_direct_raise_instance(self):
timeout = gevent.Timeout() timeout = gevent.Timeout()
try: try:
raise timeout raise timeout
except gevent.Timeout: except gevent.Timeout as t:
t = sys.exc_info()[1]
assert timeout is t, (timeout, t) assert timeout is t, (timeout, t)
assert not t.pending, repr(t) assert not t.pending, repr(t)
...@@ -32,8 +29,7 @@ class Test(greentest.TestCase): ...@@ -32,8 +29,7 @@ class Test(greentest.TestCase):
try: try:
get_hub().switch() get_hub().switch()
raise AssertionError('Must raise Timeout') raise AssertionError('Must raise Timeout')
except gevent.Timeout: except gevent.Timeout as ex:
ex = sys.exc_info()[1]
if ex is not timeout: if ex is not timeout:
raise raise
......
...@@ -2,7 +2,6 @@ import unittest ...@@ -2,7 +2,6 @@ import unittest
from gevent import socket from gevent import socket
import gevent import gevent
import errno import errno
import sys
import os import os
from test__server import SimpleStreamServer from test__server import SimpleStreamServer
...@@ -20,8 +19,7 @@ class Test(unittest.TestCase): ...@@ -20,8 +19,7 @@ class Test(unittest.TestCase):
try: try:
conn = self.makefile() conn = self.makefile()
raise AssertionError('Connection was not refused: %r' % (conn._sock, )) raise AssertionError('Connection was not refused: %r' % (conn._sock, ))
except socket.error: except socket.error as ex:
ex = sys.exc_info()[1]
if ex.args[0] != errno.ECONNREFUSED: if ex.args[0] != errno.ECONNREFUSED:
raise raise
......
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