Commits

Jeff Knupp  committed 3824663

greentests pass

  • Participants
  • Parent commits 6dcc729

Comments (0)

Files changed (83)

File gevent/_threading.py

 
 This module is missing 'Thread' class, but includes 'Queue'.
 """
-from Queue import Full, Empty
+from queue import Full, Empty
 from collections import deque
 import heapq
 from time import time as _time, sleep as _sleep

File gevent/backdoor.py

     def __init__(self, locals, conn, banner=None):
         Greenlet.__init__(self)
         self.locals = locals
-        self.desc = _fileobject(conn)
+        self.desc = makefile(conn)
         self.banner = banner
 
     def finalize(self):
                 # __builtin__.__dict__ in the latter case typing
                 # locals() at the backdoor prompt spews out lots of
                 # useless stuff
-                import __builtin__
+                import builtins
                 console.locals["__builtins__"] = __builtin__
                 console.interact(banner=self.banner)
             except SystemExit:  # raised by quit()
         SocketConsole.spawn(self.locals, conn, banner=self.banner)
 
 
-class _fileobject(socket._fileobject):
-
-    def write(self, data):
-        self._sock.sendall(data)
-
-    def isatty(self):
-        return True
-
-    def flush(self):
-        pass
-
-    def readline(self, *a):
-        return socket._fileobject.readline(self, *a).replace("\r\n", "\n")
-
-
 if __name__ == '__main__':
     if not sys.argv[1:]:
-        print ('USAGE: %s PORT' % sys.argv[0])
+        print(('USAGE: %s PORT' % sys.argv[0]))
     else:
         BackdoorServer(('127.0.0.1', int(sys.argv[1]))).serve_forever()

File gevent/baseserver.py

         elif hasattr(spawn, 'spawn'):
             self.pool = spawn
             self._spawn = spawn.spawn
-        elif isinstance(spawn, (int, long)):
+        elif isinstance(spawn, int):
             from gevent.pool import Pool
             self.pool = Pool(spawn)
             self._spawn = self.pool.spawn
             spawn(self._handle, *args)
 
     def _do_read(self):
-        for _ in xrange(self.max_accept):
+        for _ in range(self.max_accept):
             if self.full():
                 self.stop_accepting()
                 return

File gevent/coros.py

 import sys
 from gevent.hub import get_hub, getcurrent
 from gevent.timeout import Timeout
+import collections
 
 
 __all__ = ['Semaphore', 'DummySemaphore', 'BoundedSemaphore', 'RLock']
         *callback* will be called in the :class:`Hub <gevent.hub.Hub>`, so it must not use blocking gevent API.
         *callback* will be passed one argument: this instance.
         """
-        if not callable(callback):
+        if not isinstance(callback, collections.Callable):
             raise TypeError('Expected callable: %r' % (callback, ))
         self._links.append(callback)
         self._dirty = True

File gevent/event.py

 import sys
 from gevent.hub import get_hub, getcurrent, _NONE
 from gevent.timeout import Timeout
+import collections
 
 __all__ = ['Event', 'AsyncResult']
 
         *callback* will be called in the :class:`Hub <gevent.hub.Hub>`, so it must not use blocking gevent API.
         *callback* will be passed one argument: this instance.
         """
-        if not callable(callback):
+        if not isinstance(callback, collections.Callable):
             raise TypeError('Expected callable: %r' % (callback, ))
         self._links.add(callback)
         if self._flag and not self._notifier.active:
         *callback* will be called in the :class:`Hub <gevent.hub.Hub>`, so it must not use blocking gevent API.
         *callback* will be passed one argument: this instance.
         """
-        if not callable(callback):
+        if not isinstance(callback, collections.Callable):
             raise TypeError('Expected callable: %r' % (callback, ))
         self._links.add(callback)
         if self.ready() and not self._notifier.active:
     try:
         for event in events:
             event.rawlink(put)
-        for _ in xrange(len(events)):
+        for _ in range(len(events)):
             queue.get()
     finally:
         for event in events:

File gevent/greenlet.py

 from gevent.hub import greenlet, getcurrent, get_hub, GreenletExit, Waiter
 from gevent.timeout import Timeout
 from gevent.six import callable, _meth_self, moves, PY3
+import collections
 
 
 __all__ = ['Greenlet',
     __slots__ = ['callback']
 
     def __init__(self, callback):
-        if not callable(callback):
+        if not isinstance(callback, collections.Callable):
             raise TypeError("Expected callable: %r" % (callback, ))
         self.callback = callback
 
             if self.args:
                 args = [repr(x)[:50] for x in self.args]
             if self.kwargs:
-                args.extend(['%s=%s' % (key, repr(value)[:50]) for (key, value) in self.kwargs.items()])
+                args.extend(['%s=%s' % (key, repr(value)[:50]) for (key, value) in list(self.kwargs.items())])
             if args:
                 result += '(' + ', '.join(args) + ')'
             # it is important to save the result here, because once the greenlet exits '_run' attribute will be removed
 
         WARNING: the callable will be called in the HUB greenlet.
         """
-        if not callable(callback):
+        if not isinstance(callback, collections.Callable):
             raise TypeError('Expected callable: %r' % (callback, ))
         self._links.append(callback)
         if self.ready() and not self._notifier.active:
             for greenlet in greenlets:
                 greenlet.rawlink(put)
             if raise_error:
-                for _ in xrange(count):
+                for _ in range(count):
                     greenlet = queue.get()
                     if not greenlet.successful():
                         raise greenlet.exception
             else:
-                for _ in xrange(count):
+                for _ in range(count):
                     queue.get()
         except:
             if sys.exc_info()[1] is not timeout:

File gevent/hub.py

 
 
 if sys.version_info[0] >= 3:
-    basestring = (str, bytes)
+    str = (str, bytes)
 
     def exc_clear():
         pass
 else:
-    basestring = basestring
+    str = str
     exc_clear = sys.exc_clear
 
 
             except ImportError:
                 error = sys.exc_info()[1]
         raise error
-    if not isinstance(path, basestring):
+    if not isinstance(path, str):
         return path
     if '.' not in path:
         raise ImportError("Cannot import %r (required format: module.class)" % path)
 
 def config(default, envvar):
     result = os.environ.get(envvar) or default
-    if isinstance(result, basestring):
+    if isinstance(result, str):
         return result.split(',')
     return result
 
         else:
             try:
                 info = self.loop._format()
-            except Exception, ex:
+            except Exception as ex:
                 info = str(ex) or repr(ex) or 'error'
         result = '<%s at 0x%x %s' % (self.__class__.__name__, id(self), info)
         if self._resolver is not None:

File gevent/monkey.py

     target = getattr(source, '__target__', name)
     dest = __import__(target)
     original = getattr(dest, 'monkey_original', dest)
-    if isinstance(items, basestring):
+    if isinstance(items, str):
         return getattr(original, items)
     else:
         results = []
 
 
 if __name__ == '__main__':
-    modules = [x.replace('patch_', '') for x in globals().keys() if x.startswith('patch_') and x != 'patch_all']
+    modules = [x.replace('patch_', '') for x in list(globals().keys()) if x.startswith('patch_') and x != 'patch_all']
     script_help = """gevent.monkey - monkey patch the standard modules to use gevent.
 
 USAGE: python -m gevent.monkey [MONKEY OPTIONS] script [SCRIPT OPTIONS]
     if verbose:
         import pprint
         import os
-        print ('gevent.monkey.patch_all(%s)' % ', '.join('%s=%s' % item for item in args.items()))
-        print ('sys.version=%s' % (sys.version.strip().replace('\n', ' '), ))
-        print ('sys.path=%s' % pprint.pformat(sys.path))
-        print ('sys.modules=%s' % pprint.pformat(sorted(sys.modules.keys())))
-        print ('cwd=%s' % os.getcwd())
+        print(('gevent.monkey.patch_all(%s)' % ', '.join('%s=%s' % item for item in list(args.items()))))
+        print(('sys.version=%s' % (sys.version.strip().replace('\n', ' '), )))
+        print(('sys.path=%s' % pprint.pformat(sys.path)))
+        print(('sys.modules=%s' % pprint.pformat(sorted(sys.modules.keys()))))
+        print(('cwd=%s' % os.getcwd()))
 
     patch_all(**args)
     if argv:
         sys.argv = argv
         __package__ = None
-        execfile(sys.argv[0])
+        exec(compile(open(sys.argv[0]).read(), sys.argv[0], 'exec'))
     else:
         print (script_help)

File gevent/pool.py

     def __iter__(self):
         return self
 
-    def next(self):
+    def __next__(self):
         value = self.queue.get()
         if isinstance(value, Failure):
             raise value.exc
         return value
 
-    if six.PY3:
-        __next__ = next
-        del next
-
     def _run(self):
         try:
             func = self.func
     def __iter__(self):
         return self
 
-    def next(self):
+    def __next__(self):
         while True:
             if self.waiting and self.waiting[0][0] <= self.index:
                 index, value = self.waiting.pop(0)
             if value is not _SKIP:
                 return value
 
-    if six.PY3:
-        __next__ = next
-        del next
-
     def _run(self):
         try:
             func = self.func

File gevent/pywsgi.py

 import sys
 import time
 import traceback
-import mimetools
+from email.mime.message import MIMEMessage
 from datetime import datetime
-from urllib import unquote
+from urllib.parse import unquote
 
 from gevent import socket
 import gevent
     def __iter__(self):
         return self
 
-    def next(self):
+    def __next__(self):
         line = self.readline()
         if not line:
             raise StopIteration
 
 class WSGIHandler(object):
     protocol_version = 'HTTP/1.1'
-    MessageClass = mimetools.Message
+    MessageClass = MIMEMessage
 
     def __init__(self, socket, address, server, rfile=None):
         self.socket = socket
         msg = ''.join(towrite)
         try:
             self.socket.sendall(msg)
-        except socket.error, ex:
+        except socket.error as ex:
             self.status = 'socket error: %s' % ex
             if self.code > 0:
                 self.code = -self.code
             try:
                 if self.headers_sent:
                     # Re-raise original exception if headers sent
-                    raise exc_info[0], exc_info[1], exc_info[2]
+                    raise exc_info[0](exc_info[1]).with_traceback(exc_info[2])
             finally:
                 # Avoid dangling circular ref
                 exc_info = None

File gevent/queue.py

 import collections
 
 try:
-    from Queue import Full, Empty
+    from queue import Full, Empty
 except ImportError:
     __queue__ = __import__('queue')
     Full = __queue__.Full
     def __iter__(self):
         return self
 
-    def next(self):
+    def __next__(self):
         result = self.get()
         if result is StopIteration:
             raise result
     def __iter__(self):
         return self
 
-    def next(self):
+    def __next__(self):
         result = self.get()
         if result is StopIteration:
             raise result

File gevent/resolver_ares.py

 import os
 import sys
 from _socket import getservbyname, getaddrinfo, gaierror, error
-from gevent.hub import Waiter, get_hub, basestring
+from gevent.hub import Waiter, get_hub, str
 from gevent.socket import AF_UNSPEC, AF_INET, AF_INET6, SOCK_STREAM, SOCK_DGRAM, SOCK_RAW, AI_NUMERICHOST, EAI_SERVICE, AI_PASSIVE
 from gevent.ares import channel, InvalidIP
 
                 # "self.ares is not ares" means channel was destroyed (because we were forked)
 
     def _lookup_port(self, port, socktype):
-        if isinstance(port, basestring):
+        if isinstance(port, str):
             try:
                 port = int(port)
             except ValueError:
         return port, socktype
 
     def _getaddrinfo(self, host, port, family=0, socktype=0, proto=0, flags=0):
-        if isinstance(host, unicode):
+        if isinstance(host, str):
             host = host.encode('idna')
         elif not isinstance(host, str) or (flags & AI_NUMERICHOST):
             # this handles cases which do not require network access

File gevent/select.py

     try:
         fileno_f = obj.fileno
     except AttributeError:
-        if not isinstance(obj, (int, long)):
+        if not isinstance(obj, int):
             raise TypeError('argument must be an int, or have a fileno() method: %r' % (obj, ))
         return obj
     else:

File gevent/server.py

     def do_read(self):
         try:
             client_socket, address = self.socket.accept()
-        except _socket.error, err:
+        except _socket.error as err:
             if err[0] == EWOULDBLOCK:
                 return
             raise
     def do_read(self):
         try:
             data, address = self._socket.recvfrom(8192)
-        except _socket.error, err:
+        except _socket.error as err:
             if err[0] == EWOULDBLOCK:
                 return
             raise

File gevent/six.py

 
     MAXSIZE = sys.maxsize
 else:
-    string_types = basestring,
-    integer_types = (int, long)
-    class_types = (type, types.ClassType)
-    text_type = unicode
+    string_types = str,
+    integer_types = (int, int)
+    class_types = (type, type)
+    text_type = str
     binary_type = str
 
     # It's possible to have sizeof(long) != sizeof(Py_ssize_t).
         return any("__call__" in klass.__dict__ for klass in type(obj).__mro__)
 else:
     def get_unbound_function(unbound):
-        return unbound.im_func
+        return unbound.__func__
 
 
     def advance_iterator(it):
-        return it.next()
+        return next(it)
 
     callable = callable
 _add_doc(get_unbound_function,
     def b(s):
         return s
     def u(s):
-        return unicode(s, "unicode_escape")
+        return str(s, "unicode_escape")
     int2byte = chr
-    import StringIO
-    StringIO = BytesIO = StringIO.StringIO
+    import io
+    StringIO = BytesIO = io.StringIO
 _add_doc(b, """Byte literal""")
 _add_doc(u, """Text literal""")
 
         if fp is None:
             return
         def write(data):
-            if not isinstance(data, basestring):
+            if not isinstance(data, str):
                 data = str(data)
             fp.write(data)
         want_unicode = False
         sep = kwargs.pop("sep", None)
         if sep is not None:
-            if isinstance(sep, unicode):
+            if isinstance(sep, str):
                 want_unicode = True
             elif not isinstance(sep, str):
                 raise TypeError("sep must be None or a string")
         end = kwargs.pop("end", None)
         if end is not None:
-            if isinstance(end, unicode):
+            if isinstance(end, str):
                 want_unicode = True
             elif not isinstance(end, str):
                 raise TypeError("end must be None or a string")
             raise TypeError("invalid keyword arguments to print()")
         if not want_unicode:
             for arg in args:
-                if isinstance(arg, unicode):
+                if isinstance(arg, str):
                     want_unicode = True
                     break
         if want_unicode:
-            newline = unicode("\n")
-            space = unicode(" ")
+            newline = str("\n")
+            space = str(" ")
         else:
             newline = "\n"
             space = " "

File gevent/socket.py

 
 import sys
 import time
-from gevent.hub import get_hub, basestring
+from gevent.hub import get_hub, str
 from gevent.timeout import Timeout
 
 is_windows = sys.platform == 'win32'
 import _socket
 _realsocket = _socket.socket
 __socket__ = __import__('socket')
-_fileobject = __socket__._fileobject
+#_fileobject = __socket__._fileobject
 
 for name in __imports__[:]:
     try:
 
 for name in __socket__.__all__:
     value = getattr(__socket__, name)
-    if isinstance(value, (int, long, basestring)):
+    if isinstance(value, (int, str)):
         globals()[name] = value
         __imports__.append(name)
 
         Note, that the new socket does not inherit the timeout."""
         return socket(_sock=self._sock)
 
-    def makefile(self, mode='r', bufsize=-1):
-        # note that this does not inherit timeout either (intentionally, because that's
-        # how the standard socket behaves)
-        return _fileobject(self.dup(), mode, bufsize)
-
     def recv(self, *args):
         sock = self._sock  # keeping the reference so that fd is not closed during waiting
         while True:
                 raise
 
     def sendall(self, data, flags=0):
-        if isinstance(data, unicode):
+        if isinstance(data, str):
             data = data.encode()
         # this sendall is also reused by gevent.ssl.SSLSocket subclass,
         # so it should not call self._sock methods directly
 
     # delegate the functions that we haven't implemented to the real 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))
-    del _m, _s
+    #_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))
+    #del _m, _s
+    def setsockopt(self, *args): return self._sock.setsockopt(*args)
+    def bind(self, *args): return self._sock.bind(*args)
+    def listen(self, *args): return self._sock.listen(*args)
+    def getsockname(self, *args): return self._sock.getsockname(*args)
+    def fileno(self, *args): return self._sock.fileno(*args)
 
 SocketType = socket
 

File gevent/ssl.py

 
 import sys
 import errno
-from gevent.socket import socket, _fileobject, timeout_default
+from ssl import CertificateError, SSLContext, match_hostname
+from gevent.socket import socket, timeout_default
 from gevent.socket import error as socket_error, EBADF
-from gevent.hub import basestring
+from gevent.hub import str
 
 __implements__ = ['SSLSocket',
                   'wrap_socket',
-                  'get_server_certificate',
-                  'sslwrap_simple']
+                  'get_server_certificate', ]
 
 __imports__ = ['SSLError',
                'RAND_status',
 for name in dir(__ssl__):
     if not name.startswith('_'):
         value = getattr(__ssl__, name)
-        if isinstance(value, (int, long, basestring, tuple)):
+        if isinstance(value, (int, str, tuple)):
             globals()[name] = value
             __imports__.append(name)
 
         # see if it's connected
         try:
             socket.getpeername(self)
-        except socket_error, e:
+        except socket_error as e:
             if e[0] != errno.ENOTCONN:
                 raise
             # no, no connection yet
         self._makefile_refs += 1
         # close=True so as to decrement the reference count when done with
         # the file-like object.
-        return _fileobject(self, mode, bufsize, close=True)
+        return _sock.makefile(self, mode, bufsize, close=True)
 
 
 _SSLErrorReadTimeout = SSLError('The read operation timed out')
     dercert = s.getpeercert(True)
     s.close()
     return DER_cert_to_PEM_cert(dercert)
-
-
-def sslwrap_simple(sock, keyfile=None, certfile=None):
-    """A replacement for the old socket.ssl function.  Designed
-    for compability with Python 2.5 and earlier.  Will disappear in
-    Python 3.0."""
-    return SSLSocket(sock, keyfile, certfile)

File gevent/thread.py

 """
 import sys
 
-__implements__ = ['allocate_lock',
+__all__ = ['allocate_lock',
                   'get_ident',
                   'exit',
                   'LockType',
             pass
             # not going to decrease stack_size, because otherwise other greenlets in this thread will suffer
 else:
-    __implements__.remove('stack_size')
+    __all__.remove('stack_size')
 
 
-__all__ = __implements__ + __imports__
 __all__.remove('_local')
 
 # XXX interrupt_main

File gevent/threadpool.py

 # Copyright (c) 2012 Denis Bilenko. See LICENSE for details.
-from __future__ import with_statement
+
 import sys
 import os
 from gevent.hub import get_hub, sleep

File gevent/timeout.py

 """
 
 import sys
-from gevent.hub import getcurrent, _NONE, get_hub, basestring
+from gevent.hub import getcurrent, _NONE, get_hub, str
 
 __all__ = ['Timeout',
            'with_timeout']
         assert not self.pending, '%r is already started; to restart it, cancel it first' % self
         if self.seconds is None:  # "fake" timeout (never expires)
             pass
-        elif self.exception is None or self.exception is False or isinstance(self.exception, basestring):
+        elif self.exception is None or self.exception is False or isinstance(self.exception, str):
             # timeout that raises self
             self.timer.start(getcurrent().throw, self)
         else:  # regular timeout with user-provided exception

File gevent/win32util.py

         except ImportError:
             FormatMessage = None
         try:
-            from socket import errorTab
+            from .socket import errorTab
         except ImportError:
             errorTab = None
         return cls(WinError, FormatMessage, errorTab)

File greentest/bench_sendall.py

         start = time.time()
         conn.sendall(data)
         spent = time.time() - start
-        print ("%.2f MB/s" % (length / spent / 0x100000))
+        print(("%.2f MB/s" % (length / spent / 0x100000)))
         spent_total += spent
 
-    print ("~ %.2f MB/s" % (length * N / spent_total / 0x100000))
+    print(("~ %.2f MB/s" % (length * N / spent_total / 0x100000)))
     server.stop()
 
 

File greentest/bench_sleep0.py

 while True:
     start = time()
     user_time, system_time = os.times()[:2]
-    for _ in xrange(N):
+    for _ in range(N):
         sleep(0)
     user_time_x, system_time_x = os.times()[:2]
     delta = time() - start
 user_time_x -= user_time
 system_time_x -= system_time
 ms = 1000000. / N
-print 'N=%s delta=%s utime=%s stime=%s' % (N, delta, user_time_x, system_time_x)
-print ('sleep(0): %.1f, utime: %.1f, stime: %.1f (microseconds)' % (delta * ms, user_time_x * ms, system_time_x * ms))
+print('N=%s delta=%s utime=%s stime=%s' % (N, delta, user_time_x, system_time_x))
+print(('sleep(0): %.1f, utime: %.1f, stime: %.1f (microseconds)' % (delta * ms, user_time_x * ms, system_time_x * ms)))

File greentest/bench_spawn.py

 
 def test(spawn, sleep, kwargs):
     start = time()
-    for _ in xrange(N):
+    for _ in range(N):
         spawn(incr, sleep, **kwargs)
     delta = time() - start
-    print ('spawning: %.1f microseconds per greenlet' % (delta * 1000000.0 / N))
+    print(('spawning: %.1f microseconds per greenlet' % (delta * 1000000.0 / N)))
     assert counter == 0, counter
     start = time()
     sleep(0)
     delta = time() - start
     assert counter == N, (counter, N)
-    print ('sleep(0): %.1f microseconds per greenlet' % (delta * 1000000.0 / N))
+    print(('sleep(0): %.1f microseconds per greenlet' % (delta * 1000000.0 / N)))
 
 
 def bench_none(options):
     kwargs = options.kwargs
     start = time()
-    for _ in xrange(N):
+    for _ in range(N):
         incr(noop, **kwargs)
     delta = time() - start
     assert counter == N, (counter, N)
-    print ('%.2f microseconds' % (delta * 1000000.0 / N))
+    print(('%.2f microseconds' % (delta * 1000000.0 / N)))
 
 
 def bench_gevent(options):
     import gevent
-    print ('using gevent from %s' % gevent.__file__)
+    print(('using gevent from %s' % gevent.__file__))
     from gevent import spawn, sleep
     test(spawn, sleep, options.kwargs)
 
 
 def bench_geventraw(options):
     import gevent
-    print ('using gevent from %s' % gevent.__file__)
+    print(('using gevent from %s' % gevent.__file__))
     from gevent import sleep, spawn_raw
     test(spawn_raw, sleep, options.kwargs)
 
 
 def bench_geventpool(options):
     import gevent
-    print ('using gevent from %s' % gevent.__file__)
+    print(('using gevent from %s' % gevent.__file__))
     from gevent import sleep
     from gevent.pool import Pool
     p = Pool()
     start = time()
     p.join()
     delta = time() - start
-    print ('joining: %.1f microseconds per greenlet' % (delta * 1000000.0 / N))
+    print(('joining: %.1f microseconds per greenlet' % (delta * 1000000.0 / N)))
 
 
 def bench_eventlet(options):
         if options.ignore_import_errors:
             return
         raise
-    print ('using eventlet from %s' % eventlet.__file__)
+    print(('using eventlet from %s' % eventlet.__file__))
     from eventlet.api import spawn, sleep, use_hub
     if options.eventlet_hub is not None:
         use_hub(options.eventlet_hub)
         if options.ignore_import_errors:
             return
         raise
-    print ('using eventlet from %s' % eventlet.__file__)
+    print(('using eventlet from %s' % eventlet.__file__))
     from eventlet.proc import spawn_greenlet as spawn
     from eventlet.api import sleep, use_hub
     if options.eventlet_hub:
         time.sleep(0.01)
         if os.system(cmd):
             error = 1
-            print ('%s failed' % cmd)
+            print(('%s failed' % cmd))
         print ('')
     for func in names:
         cmd = '%s %s --with-kwargs %s --ignore-import-errors' % (sys.executable, __file__, func)
         sys.stdout.flush()
         if os.system(cmd):
             error = 1
-            print ('%s failed' % cmd)
+            print(('%s failed' % cmd))
         print ('')
     if error:
         sys.exit(1)
 def all():
     result = [x for x in globals() if x.startswith('bench_') and x != 'bench_all']
     try:
-        result.sort(key=lambda x: globals()[x].func_code.co_firstlineno)
+        result.sort(key=lambda x: globals()[x].__code__.co_firstlineno)
     except AttributeError:
         result.sort(key=lambda x: globals()[x].__code__.co_firstlineno)
     result = [x.replace('bench_', '') for x in result]

File greentest/greentest.py

 # THE SOFTWARE.
 
 # package is named greentest, not test, so it won't be confused with test in stdlib
-from __future__ import with_statement
+
 import sys
 import unittest
 from unittest import TestCase as BaseTestCase
 from patched_tests_setup import get_switch_expected
 from gevent.hub import _get_hub
 from functools import wraps
+import collections
 
 VERBOSE = sys.argv.count('-v') > 1
 
                 timeout *= 6
         check_totalrefcount = _get_class_attr(classDict, bases, 'check_totalrefcount', True)
         error_fatal = _get_class_attr(classDict, bases, 'error_fatal', True)
-        for key, value in classDict.items():
-            if key.startswith('test') and callable(value):
+        for key, value in list(classDict.items()):
+            if key.startswith('test') and isinstance(value, collections.Callable):
                 classDict.pop(key)
                 value = wrap_timeout(timeout, value)
                 my_error_fatal = getattr(value, 'error_fatal', None)
         return type.__new__(meta, classname, bases, classDict)
 
 
-class TestCase(BaseTestCase):
+class TestCase(BaseTestCase, metaclass=TestCaseMetaClass):
 
-    __metaclass__ = TestCaseMetaClass
     __timeout__ = 1
     switch_expected = 'default'
     error_fatal = True

File greentest/helper.py

     module_source = disable_tests_in_source(module_source, name)
     module_code = compile(module_source, _filename, 'exec')
 
-    print >> sys.stderr, 'Testing %s with monkey patching' % _filename
+    print('Testing %s with monkey patching' % _filename, file=sys.stderr)
     return module_code

File greentest/lock_tests.py

 """
 Various tests for synchronization primitives.
 """
-from __future__ import with_statement
+
 
 import sys
 import time
-from thread import start_new_thread, get_ident
+from _thread import start_new_thread, get_ident
 import threading
 import unittest
 
 
     def test_constructor(self):
         self.assertRaises(ValueError, self.semtype, value = -1)
-        self.assertRaises(ValueError, self.semtype, value = -sys.maxint)
+        self.assertRaises(ValueError, self.semtype, value = -sys.maxsize)
 
     def test_acquire(self):
         sem = self.semtype(1)

File greentest/patched_test.py

 import helper
-exec helper.prepare_stdlib_test(__file__) in globals()
+exec(helper.prepare_stdlib_test(__file__), globals())

File greentest/patched_tests_setup.py

         # XXX ignoring TestCase class name
         testcase = test.split('.')[-1]
         source, n = re.subn(testcase, 'XXX' + testcase, source)
-        print >> sys.stderr, 'Removed %s (%d)' % (testcase, n)
+        print('Removed %s (%d)' % (testcase, n), file=sys.stderr)
     return source

File greentest/test__all__.py

 ANY = ANY()
 
 NOT_IMPLEMENTED = {
-    'socket': ['CAPI', 'gethostbyaddr', 'gethostbyname_ex', 'getnameinfo'],
+    'socket': ['CAPI', 'gethostbyaddr', 'gethostbyname_ex', 'getnameinfo', 'dup'],
     'thread': ['allocate', 'exit_thread', 'interrupt_main', 'start_new'],
     'select': ANY}
 
     def check_all(self):
         "Check that __all__ is present and does not contain invalid entries"
         names = {}
-        exec ("from %s import *" % self.modname) in names
+        exec(("from %s import *" % self.modname), names)
         names.pop('__builtins__', None)
         self.assertEqual(sorted(names), sorted(self.module.__all__))
 
             result = []
             for name in missed[:]:
                 if name in not_implemented:
-                    print ('IncompleteImplWarning: %s.%s' % (self.modname, name))
+                    print(('IncompleteImplWarning: %s.%s' % (self.modname, name)))
                 else:
                     result.append(name)
             missed = result
 
     def _test(self, modname):
         self.modname = modname
-        exec "import %s" % modname in {}
+        exec("import %s" % modname, {})
         self.module = sys.modules[modname]
 
         if modname == 'gevent.six':

File greentest/test__api_timeout.py

 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 # THE SOFTWARE.
 
-from __future__ import with_statement
+
 import sys
 import greentest
 import weakref

File greentest/test__backdoor.py

             line = conn.makefile().readline()
             assert line.strip() == '4', repr(line)
 
-        jobs = [gevent.spawn(connect) for _ in xrange(10)]
+        jobs = [gevent.spawn(connect) for _ in range(10)]
         gevent.joinall(jobs)
         server.close()
         #self.assertEqual(conn.recv(1), '')

File greentest/test__core_stat.py

     with gevent.Timeout(timeout):
         hub.wait(watcher)
 
-    print 'Watcher %r reacted after %.6f seconds' % (watcher, time.time() - start - 0.2)
+    print('Watcher %r reacted after %.6f seconds' % (watcher, time.time() - start - 0.2))
 
     gevent.spawn_later(0.2, unlink)
 
     with gevent.Timeout(timeout):
         hub.wait(watcher)
 
-    print 'Watcher %r reacted after %.2f seconds' % (watcher, time.time() - start - 0.2)
+    print('Watcher %r reacted after %.2f seconds' % (watcher, time.time() - start - 0.2))
 
 finally:
     unlink()

File greentest/test__core_timer.py

     gettotalrefcount = getattr(sys, 'gettotalrefcount', None)
     called[:] = []
     if gettotalrefcount is not None:
-        print (gettotalrefcount())
+        print((gettotalrefcount()))
     main()
     called[:] = []
     if gettotalrefcount is not None:
-        print (gettotalrefcount())
+        print((gettotalrefcount()))

File greentest/test__doctests.py

             if re.search('^\s*>>> ', open(path).read(), re.M):
                 try:
                     s = doctest.DocTestSuite(m, extraglobs=globs)
-                    print ('%s (from %s): %s tests' % (m, path, len(s._tests)))
+                    print(('%s (from %s): %s tests' % (m, path, len(s._tests))))
                     suite.addTest(s)
                     modules_count += 1
                     tests_count += len(s._tests)
                 except Exception:
                     traceback.print_exc()
                     sys.stderr.write('Failed to process %s\n\n' % path)
-        print ('Total: %s tests in %s modules' % (tests_count, modules_count))
+        print(('Total: %s tests in %s modules' % (tests_count, modules_count)))
         runner = unittest.TextTestRunner(verbosity=2)
         runner.run(suite)
     finally:

File greentest/test__examples.py

 import glob
 from os.path import join, abspath, dirname, normpath, basename
 import unittest
+import collections
 try:
-    import urllib2
+    import urllib.request, urllib.error, urllib.parse
 except ImportError:
     from urllib import request as urllib2
 import time
 def make_test(path):
 
     if sys.platform == 'win32' and os.path.basename(path) in ('geventsendfile.py', 'processes.py'):
-        print 'Ignoring', path
+        print('Ignoring', path)
         return
 
     if ' ' in path:
     def read(self, path='/'):
         url = self.URL + path
         try:
-            response = urllib2.urlopen(url)
-        except urllib2.HTTPError:
+            response = urllib.request.urlopen(url)
+        except urllib.error.HTTPError:
             response = sys.exc_info()[1]
         return '%s %s' % (response.code, response.msg), response.read()
 
         for method in dir(self):
             if method.startswith('_test'):
                 function = getattr(self, method)
-                if callable(function):
+                if isinstance(function, collections.Callable):
                     function()
 
 
 
 
 tests = set()
-for klass in globals().keys():
+for klass in list(globals().keys()):
     if klass.startswith('Test'):
         path = getattr(globals()[klass], 'path', None)
         if path is not None:
     test = make_test(example)
     if test is not None:
         globals()[test.__name__] = test
-        print ('Added %s' % test.__name__)
+        print(('Added %s' % test.__name__))
     del test
 
 

File greentest/test__greenness.py

 monkey.patch_all()
 import sys
 try:
-    import urllib2
+    import urllib.request, urllib.error, urllib.parse
 except ImportError:
     from urllib import request as urllib2
 try:
-    import BaseHTTPServer
+    import http.server
 except ImportError:
     from http import server as BaseHTTPServer
 import gevent
 
     def test_urllib2(self):
         server_address = ('', 0)
-        BaseHTTPServer.BaseHTTPRequestHandler.protocol_version = "HTTP/1.0"
-        self.httpd = BaseHTTPServer.HTTPServer(server_address, BaseHTTPServer.BaseHTTPRequestHandler)
+        http.server.BaseHTTPRequestHandler.protocol_version = "HTTP/1.0"
+        self.httpd = http.server.HTTPServer(server_address, http.server.BaseHTTPRequestHandler)
         self.httpd.request_count = 0
         server = gevent.spawn(self.serve)
 
         port = self.httpd.socket.getsockname()[1]
         try:
-            urllib2.urlopen('http://127.0.0.1:%s' % port)
+            urllib.request.urlopen('http://127.0.0.1:%s' % port)
             assert False, 'should not get there'
-        except urllib2.HTTPError:
+        except urllib.error.HTTPError:
             ex = sys.exc_info()[1]
             assert ex.code == 501, repr(ex)
         server.get(0.01)

File greentest/test__monkey.py

 import time
 assert 'built-in' not in repr(time.sleep), repr(time.sleep)
 
-import thread
+import _thread
 import threading
-assert 'built-in' not in repr(thread.start_new_thread), repr(thread.start_new_thread)
+assert 'built-in' not in repr(_thread.start_new_thread), repr(_thread.start_new_thread)
 assert 'built-in' not in repr(threading._start_new_thread), repr(threading._start_new_thread)
 assert 'built-in' not in repr(threading._sleep), repr(threading._sleep)
 

File greentest/test__pool.py

 
     def test_map(self):
         pmap = self.pool.map
-        self.assertEqual(pmap(sqr, range(10)), list(map(sqr, range(10))))
-        self.assertEqual(pmap(sqr, range(100)), list(map(sqr, range(100))))
+        self.assertEqual(pmap(sqr, list(range(10))), list(map(sqr, list(range(10)))))
+        self.assertEqual(pmap(sqr, list(range(100))), list(map(sqr, list(range(100)))))
 
     def test_async(self):
         res = self.pool.apply_async(sqr, (7, TIMEOUT1,))
         self.pool.join()
 
     def test_imap(self):
-        it = self.pool.imap(sqr, range(10))
-        self.assertEqual(list(it), list(map(sqr, range(10))))
+        it = self.pool.imap(sqr, list(range(10)))
+        self.assertEqual(list(it), list(map(sqr, list(range(10)))))
 
-        it = self.pool.imap(sqr, range(10))
+        it = self.pool.imap(sqr, list(range(10)))
         for i in range(10):
             self.assertEqual(six.advance_iterator(it), i * i)
         self.assertRaises(StopIteration, lambda: six.advance_iterator(it))
 
-        it = self.pool.imap(sqr, range(1000))
+        it = self.pool.imap(sqr, list(range(1000)))
         for i in range(1000):
             self.assertEqual(six.advance_iterator(it), i * i)
         self.assertRaises(StopIteration, lambda: six.advance_iterator(it))
 
     def test_imap_random(self):
-        it = self.pool.imap(sqr_random_sleep, range(10))
-        self.assertEqual(list(it), list(map(sqr, range(10))))
+        it = self.pool.imap(sqr_random_sleep, list(range(10)))
+        self.assertEqual(list(it), list(map(sqr, list(range(10)))))
 
     def test_imap_unordered(self):
-        it = self.pool.imap_unordered(sqr, range(1000))
-        self.assertEqual(sorted(it), list(map(sqr, range(1000))))
+        it = self.pool.imap_unordered(sqr, list(range(1000)))
+        self.assertEqual(sorted(it), list(map(sqr, list(range(1000)))))
 
-        it = self.pool.imap_unordered(sqr, range(1000))
-        self.assertEqual(sorted(it), list(map(sqr, range(1000))))
+        it = self.pool.imap_unordered(sqr, list(range(1000)))
+        self.assertEqual(sorted(it), list(map(sqr, list(range(1000)))))
 
     def test_imap_unordered_random(self):
-        it = self.pool.imap_unordered(sqr_random_sleep, range(10))
-        self.assertEqual(sorted(it), list(map(sqr, range(10))))
+        it = self.pool.imap_unordered(sqr_random_sleep, list(range(10)))
+        self.assertEqual(sorted(it), list(map(sqr, list(range(10)))))
 
     def test_terminate(self):
         result = self.pool.map_async(gevent.sleep, [0.1] * ((self.size or 10) * 2))

File greentest/test__pywsgi.py

 import cgi
 import os
 import sys
-import StringIO
+import io
 try:
     from wsgiref.validate import validator
 except ImportError:
         try:
             key, value = line.split(': ', 1)
         except:
-            print 'Failed to split: %r' % (line, )
+            print('Failed to split: %r' % (line, ))
             raise
-        assert key.lower() not in [x.lower() for x in headers.keys()], 'Header %r:%r sent more than once: %r' % (key, value, headers)
+        assert key.lower() not in [x.lower() for x in list(headers.keys())], 'Header %r:%r sent more than once: %r' % (key, value, headers)
         headers[key] = value
     return response_line, headers
 
         try:
             chunk_size = int(chunk_size, 16)
         except:
-            print 'Failed to parse chunk size: %r' % line
+            print('Failed to parse chunk size: %r' % line)
             raise
         if chunk_size == 0:
             crlf = fd.read(2)
         try:
             version, code, self.reason = status_line[:-2].split(' ', 2)
         except Exception:
-            print 'Error: %r' % status_line
+            print('Error: %r' % status_line)
             raise
         self.code = int(code)
         HTTP, self.version = version.split('/')
         try:
             if 'chunked' in headers.get('Transfer-Encoding', ''):
                 if CONTENT_LENGTH in headers:
-                    print "WARNING: server used chunked transfer-encoding despite having Content-Length header (libevent 1.x's bug)"
+                    print("WARNING: server used chunked transfer-encoding despite having Content-Length header (libevent 1.x's bug)")
                 self.chunks = list(iread_chunks(fd))
                 self.body = ''.join(self.chunks)
             elif CONTENT_LENGTH in headers:
             else:
                 self.body = fd.read()
         except:
-            print 'Response.read failed to read the body:\n%s' % self
+            print('Response.read failed to read the body:\n%s' % self)
             raise
         if body is not None:
             self.assertBody(body)
     def read(self, *args):
         result = self.obj.read(*args)
         if DEBUG:
-            print repr(result)
+            print(repr(result))
         return result
 
     def readline(self, *args):
         result = self.obj.readline(*args)
         if DEBUG:
-            print repr(result)
+            print(repr(result))
         return result
 
     def __getattr__(self, item):
     def test_short_read_with_zero_content_length(self):
         body = self.body()
         req = "POST /short-read HTTP/1.1\r\ntransfer-encoding: Chunked\r\nContent-Length:0\r\n\r\n" + body
-        print "REQUEST:", repr(req)
+        print("REQUEST:", repr(req))
 
         fd = self.connect().makefile(bufsize=1)
         fd.write(req)
             ex = sys.exc_info()[1]
             if str(ex).startswith('Unexpected code: 400'):
                 if not server_implements_chunked:
-                    print 'ChunkedNotImplementedWarning'
+                    print('ChunkedNotImplementedWarning')
                     return
             raise
 
             ex = sys.exc_info()[1]
             if str(ex).startswith('Unexpected code: 400'):
                 if not server_implements_100continue:
-                    print '100ContinueNotImplementedWarning'
+                    print('100ContinueNotImplementedWarning')
                     return
             raise
 
     # check that WSGIServer does not insert any default values for CONTENT_LENGTH
 
     def application(self, environ, start_response):
-        for key, value in environ.items():
+        for key, value in list(environ.items()):
             if key in ('CONTENT_LENGTH', 'CONTENT_TYPE') or key.startswith('HTTP_'):
                 if key != 'HTTP_HOST':
                     raise AssertionError('Unexpected environment variable: %s=%r' % (key, value))
             data = chunk_encode(data)
             chunked_input = True
 
-        return Input(StringIO.StringIO(data), content_length=content_length, chunked_input=chunked_input)
+        return Input(io.StringIO(data), content_length=content_length, chunked_input=chunked_input)
 
     def test_short_post(self):
         i = self.make_input("1", content_length=2)

File greentest/test__refcount.py

 from gevent import monkey; monkey.patch_all()
 
 from pprint import pformat
-from thread import start_new_thread
+from _thread import start_new_thread
 from time import sleep
 import weakref
 import gc
 def run_and_check(run_client):
     w = run_interaction(run_client=run_client)
     if w():
-        print pformat(gc.get_referrers(w()))
+        print(pformat(gc.get_referrers(w())))
         for x in gc.get_referrers(w()):
-            print pformat(x)
+            print(pformat(x))
             for y in gc.get_referrers(x):
-                print '-', pformat(y)
+                print('-', pformat(y))
         raise AssertionError('server should be dead by now')
 
 

File greentest/test__select.py

         select.select([int(sock.fileno())], [], [], 0.001)
 
     try:
-        long
+        int
     except NameError:
         pass
     else:
         def test_long(self):
             sock = socket.socket()
-            select.select([long(sock.fileno())], [], [], 0.001)
+            select.select([int(sock.fileno())], [], [], 0.001)
 
     def test_string(self):
         self.switch_expected = False

File greentest/test__server.py

         try:
             method, path, rest = request_line.split(' ', 3)
         except Exception:
-            print ('Failed to parse request line: %r' % (request_line, ))
+            print(('Failed to parse request line: %r' % (request_line, )))
             raise
         if path == '/ping':
             client_socket.sendall('HTTP/1.0 200 OK\r\n\r\nPONG')

File greentest/test__socket.py

         self.sendall(self.long_data)
 
     def test_sendall_unicode(self):
-        self.sendall(unicode(self.long_data))
+        self.sendall(str(self.long_data))
 
     def test_sendall_array(self):
         data = array.array("B", self.long_data)
             data_read = conn.makefile().read()
             self.assertEqual(len(data_sent), len(data_read))
             self.assertEqual(data_sent, data_read)
-            print '%s: WARNING: read the data instead of failing with timeout' % self.__class__.__name__
+            print('%s: WARNING: read the data instead of failing with timeout' % self.__class__.__name__)
 
     def test_makefile(self):
         def accept_once():
         sock.close()
         try:
             sock.send('a', timeout=1)
-        except socket.error, ex:
+        except socket.error as ex:
             if ex.errno != 9:
                 raise
 

File greentest/test__socket_dns.py

 #!/usr/bin/python
 # -*- coding: utf-8 -*-
-from __future__ import with_statement
+
 import sys
 import re
 import traceback
         try:
             result = function(*args)
             raise AssertionError('%s: Expected to raise %s, instead returned %r' % (function, error, result))
-        except Exception, ex:
-            if isinstance(error, basestring):
+        except Exception as ex:
+            if isinstance(error, str):
                 repr_error = error
             else:
                 repr_error = repr(error)
 class TestInternational(TestCase):
     switch_expected = None
 
-add(TestInternational, u'президент.рф', 'russian')
-add(TestInternational, u'президент.рф'.encode('idna'), 'idna')
+add(TestInternational, 'президент.рф', 'russian')
+add(TestInternational, 'президент.рф'.encode('idna'), 'idna')
 
 
 

File greentest/test__socket_ssl.py

 import sys
 import unittest
 try:
-    import httplib
+    import http.client
 except ImportError:
     from http import client as httplib
 import socket
 class AmazonHTTPSTests(unittest.TestCase):
 
     def test_amazon_response(self):
-        conn = httplib.HTTPSConnection('sdb.amazonaws.com')
+        conn = http.client.HTTPSConnection('sdb.amazonaws.com')
         conn.debuglevel = 1
         conn.request('GET', '/')
         conn.getresponse()

File greentest/test__threading_vs_settrace.py

-from __future__ import with_statement
+
 
 import sys
 import subprocess
         try:
             def trace(frame, ev, arg):
                 lst.append((frame.f_code.co_filename, frame.f_lineno, ev))
-                print "TRACE: %s:%s %s" % lst[-1]
+                print("TRACE: %s:%s %s" % lst[-1])
                 return trace
 
             with gevent.thread.allocate_lock():

File greentest/test__threadpool.py

 
     def test_map(self):
         pmap = self.pool.map
-        self.assertEqual(pmap(sqr, range(10)), list(map(sqr, range(10))))
-        self.assertEqual(pmap(sqr, range(100)), list(map(sqr, range(100))))
+        self.assertEqual(pmap(sqr, list(range(10))), list(map(sqr, list(range(10)))))
+        self.assertEqual(pmap(sqr, list(range(100))), list(map(sqr, list(range(100)))))
 
     def test_async(self):
         res = self.pool.apply_async(sqr, (7, TIMEOUT1,))
         self.pool.join()
 
     def test_imap(self):
-        it = self.pool.imap(sqr, range(10))
-        self.assertEqual(list(it), list(map(sqr, range(10))))
+        it = self.pool.imap(sqr, list(range(10)))
+        self.assertEqual(list(it), list(map(sqr, list(range(10)))))
 
-        it = self.pool.imap(sqr, range(10))
+        it = self.pool.imap(sqr, list(range(10)))
         for i in range(10):
             self.assertEqual(six.advance_iterator(it), i * i)
         self.assertRaises(StopIteration, lambda: six.advance_iterator(it))
 
-        it = self.pool.imap(sqr, range(1000))
+        it = self.pool.imap(sqr, list(range(1000)))
         for i in range(1000):
             self.assertEqual(six.advance_iterator(it), i * i)
         self.assertRaises(StopIteration, lambda: six.advance_iterator(it))
 
     def test_imap_random(self):
-        it = self.pool.imap(sqr_random_sleep, range(10))
-        self.assertEqual(list(it), list(map(sqr, range(10))))
+        it = self.pool.imap(sqr_random_sleep, list(range(10)))
+        self.assertEqual(list(it), list(map(sqr, list(range(10)))))
 
     def test_imap_unordered(self):
-        it = self.pool.imap_unordered(sqr, range(1000))
-        self.assertEqual(sorted(it), list(map(sqr, range(1000))))
+        it = self.pool.imap_unordered(sqr, list(range(1000)))
+        self.assertEqual(sorted(it), list(map(sqr, list(range(1000)))))
 
-        it = self.pool.imap_unordered(sqr, range(1000))
-        self.assertEqual(sorted(it), list(map(sqr, range(1000))))
+        it = self.pool.imap_unordered(sqr, list(range(1000)))
+        self.assertEqual(sorted(it), list(map(sqr, list(range(1000)))))
 
     def test_imap_unordered_random(self):
-        it = self.pool.imap_unordered(sqr_random_sleep, range(10))
-        self.assertEqual(sorted(it), list(map(sqr, range(10))))
+        it = self.pool.imap_unordered(sqr_random_sleep, list(range(10)))
+        self.assertEqual(sorted(it), list(map(sqr, list(range(10)))))
 
     def test_terminate(self):
         result = self.pool.map_async(sleep, [0.1] * ((self.size or 10) * 2))

File greentest/test_ares_timeout.py

 import gevent
 from gevent.resolver_ares import Resolver
 from gevent import socket
-print gevent.__file__
+print(gevent.__file__)
 
 address = ('127.0.0.10', 53)
 listener = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
 try:
     listener.bind(address)
-except socket.error, ex:
+except socket.error as ex:
     if 'permission denied' in str(ex).lower():
         sys.stderr.write('This test binds on port 53 and thus must be run as root.\n')
         sys.exit(0)
 
 def reader():
     while True:
-        print listener.recvfrom(10000)
+        print(listener.recvfrom(10000))
 
 gevent.spawn(reader)
 
 r = gevent.get_hub().resolver = Resolver(servers=['127.0.0.10'], timeout=0.001, tries=1)
 try:
     result = r.gethostbyname('www.google.com')
-except socket.gaierror, ex:
+except socket.gaierror as ex:
     if 'ARES_ETIMEOUT' not in str(ex):
         raise
 else:

File greentest/test_close_backend_fd.py

 import gevent
 
 
-for count in xrange(2):
+for count in range(2):
     for backend in gevent.core.supported_backends():
         hub = gevent.get_hub(backend, default=False)
         assert hub.loop.backend == backend, (hub.loop.backend, backend)
         gevent.sleep(0.001)
         fileno = hub.loop.fileno()
         if fileno is not None:
-            print '%s. Testing %r: %r' % (count, backend, hub)
+            print('%s. Testing %r: %r' % (count, backend, hub))
             os.close(fileno)
             try:
                 gevent.sleep(0.001)
-            except SystemError, ex:
+            except SystemError as ex:
                 if '(libev)' in str(ex):
-                    print 'The error is expected: %s' % ex
+                    print('The error is expected: %s' % ex)
                 else:
                     raise
             else:
                 raise AssertionError('gevent.sleep() is expected to fail after loop fd was closed')
         else:
-            print '%s. %r lacks fileno()' % (count, backend)
+            print('%s. %r lacks fileno()' % (count, backend))
         hub.destroy()
         assert 'destroyed' in repr(hub), repr(hub)

File greentest/test_hub_join_timeout.py

-from __future__ import with_statement
+
 from contextlib import contextmanager
 import gevent
 from gevent.event import Event
     return expected_time(0, fuzzy=fuzzy)
 
 
-for _a in xrange(2):
+for _a in range(2):
 
     # exiting because the spawned greenlet finished execution (spawn (=callback) variant)
-    for _ in xrange(2):
+    for _ in range(2):
         x = gevent.spawn(lambda: 5)
         with no_time(SMALL):
             result = gevent.get_hub().join(timeout=10)
         assert x.value == 5, x
 
     # exiting because the spawned greenlet finished execution (spawn_later (=timer) variant)
-    for _ in xrange(2):
+    for _ in range(2):
         x = gevent.spawn_later(SMALL, lambda: 5)
         with expected_time(SMALL):
             result = gevent.get_hub().join(timeout=10)
         assert x.dead, x
 
     # exiting because of timeout (the spawned greenlet still runs)
-    for _ in xrange(2):
+    for _ in range(2):
         x = gevent.spawn_later(10, lambda: 5)
         with expected_time(SMALL):
             result = gevent.get_hub().join(timeout=SMALL)
         assert result is True
 
     # exiting because of event (the spawned greenlet still runs)
-    for _ in xrange(2):
+    for _ in range(2):
         x = gevent.spawn_later(10, lambda: 5)
         event = Event()
         event_set = gevent.spawn_later(SMALL, event.set)
         assert result is True
 
     # checking "ref=False" argument
-    for _ in xrange(2):
+    for _ in range(2):
         gevent.get_hub().loop.timer(10, ref=False).start(lambda : None)
         with no_time():
             result = gevent.get_hub().join()
         assert result is True
 
     # checking "ref=False" attribute
-    for _d in xrange(2):
+    for _d in range(2):
         w = gevent.get_hub().loop.timer(10)
         w.start(lambda : None)
         w.ref = False

File greentest/test_patched_asyncore.py

 import helper
-exec helper.prepare_stdlib_test(__file__) in globals()
+exec(helper.prepare_stdlib_test(__file__), globals())

File greentest/test_patched_ftplib.py

 import helper
-exec helper.prepare_stdlib_test(__file__) in globals()
+exec(helper.prepare_stdlib_test(__file__), globals())

File greentest/test_patched_httplib.py

 import helper
-exec helper.prepare_stdlib_test(__file__) in globals()
+exec(helper.prepare_stdlib_test(__file__), globals())

File greentest/test_patched_httpservers.py

 import helper
-exec helper.prepare_stdlib_test(__file__) in globals()
+exec(helper.prepare_stdlib_test(__file__), globals())

File greentest/test_patched_queue.py

 import helper
-exec helper.prepare_stdlib_test(__file__) in globals()
+exec(helper.prepare_stdlib_test(__file__), globals())

File greentest/test_patched_select.py

 import helper
-exec helper.prepare_stdlib_test(__file__) in globals()
+exec(helper.prepare_stdlib_test(__file__), globals())

File greentest/test_patched_signal.py

 import helper
-exec helper.prepare_stdlib_test(__file__) in globals()
+exec(helper.prepare_stdlib_test(__file__), globals())

File greentest/test_patched_smtplib.py

 import helper
-exec helper.prepare_stdlib_test(__file__) in globals()
+exec(helper.prepare_stdlib_test(__file__), globals())

File greentest/test_patched_socket.py

 import helper
-exec helper.prepare_stdlib_test(__file__) in globals()
+exec(helper.prepare_stdlib_test(__file__), globals())

File greentest/test_patched_socket_ssl.py

 import helper
-exec helper.prepare_stdlib_test(__file__) in globals()
+exec(helper.prepare_stdlib_test(__file__), globals())

File greentest/test_patched_ssl.py

 import helper
-exec helper.prepare_stdlib_test(__file__) in globals()
+exec(helper.prepare_stdlib_test(__file__), globals())

File greentest/test_patched_telnetlib.py

 import helper
-exec helper.prepare_stdlib_test(__file__) in globals()
+exec(helper.prepare_stdlib_test(__file__), globals())

File greentest/test_patched_threading.py

 import helper
-exec helper.prepare_stdlib_test(__file__) in globals()
+exec(helper.prepare_stdlib_test(__file__), globals())

File greentest/test_patched_threading_local.py

 import helper
-exec helper.prepare_stdlib_test(__file__) in globals()
+exec(helper.prepare_stdlib_test(__file__), globals())

File greentest/test_patched_timeout.py

 import helper
-exec helper.prepare_stdlib_test(__file__) in globals()
+exec(helper.prepare_stdlib_test(__file__), globals())

File greentest/test_patched_urllib.py

 import helper
-exec helper.prepare_stdlib_test(__file__) in globals()
+exec(helper.prepare_stdlib_test(__file__), globals())

File greentest/test_patched_urllib2.py

 import helper
-exec helper.prepare_stdlib_test(__file__) in globals()
+exec(helper.prepare_stdlib_test(__file__), globals())

File greentest/test_patched_urllib2_localnet.py

 import helper
-exec helper.prepare_stdlib_test(__file__) in globals()
+exec(helper.prepare_stdlib_test(__file__), globals())

File greentest/test_patched_urllib2net.py

 import helper
-exec helper.prepare_stdlib_test(__file__) in globals()
+exec(helper.prepare_stdlib_test(__file__), globals())

File greentest/test_patched_wsgiref.py

 import helper
-exec helper.prepare_stdlib_test(__file__) in globals()
+exec(helper.prepare_stdlib_test(__file__), globals())

File greentest/test_queue.py

         self.cum = 0
         for i in (0,1):
             threading.Thread(target=self.worker, args=(q,)).start()
-        for i in xrange(100):
+        for i in range(100):
             q.put(i)
         q.join()
         self.assertEquals(self.cum, sum(range(100)),

File greentest/test_socketserver.py

 test_support.requires('network')
 
 try:
-    from SocketServer import *
+    from socketserver import *
 except ImportError:
     from socketserver import *
 
         raise
 
 
-if str is unicode:
+if str is str:
     def b(s):
         return s.encode('ascii')
 else:
     for svrcls in servers:
         addr = pickaddr(proto)
         if verbose:
-            print ("ADDR = %s" % (addr,))
-            print ("CLASS = %s" % svrcls)
+            print(("ADDR = %s" % (addr,)))
+            print(("CLASS = %s" % svrcls))
         t = ServerThread(addr, svrcls, hdlrcls)
         if verbose: print ("server created")
         t.start()