python3 compatibility: print function

This commit is contained in:
Sergey Shepelev
2014-04-23 13:27:49 +04:00
parent 92d12567b2
commit 1b9f0f0edb
20 changed files with 141 additions and 132 deletions

View File

@@ -10,22 +10,21 @@ Client Pattern
The canonical client-side example is a web crawler. This use case is given a list of urls and wants to retrieve their bodies for later processing. Here is a very simple example:: The canonical client-side example is a web crawler. This use case is given a list of urls and wants to retrieve their bodies for later processing. Here is a very simple example::
import eventlet
from eventlet.green import urllib2
urls = ["http://www.google.com/intl/en_ALL/images/logo.gif", urls = ["http://www.google.com/intl/en_ALL/images/logo.gif",
"https://wiki.secondlife.com/w/images/secondlife.jpg", "https://wiki.secondlife.com/w/images/secondlife.jpg",
"http://us.i1.yimg.com/us.yimg.com/i/ww/beta/y3.gif"] "http://us.i1.yimg.com/us.yimg.com/i/ww/beta/y3.gif"]
import eventlet
from eventlet.green import urllib2
def fetch(url): def fetch(url):
return urllib2.urlopen(url).read() return urllib2.urlopen(url).read()
pool = eventlet.GreenPool()
for body in pool.imap(fetch, urls):
print "got body", len(body)
There is a slightly more complex version of this in the :ref:`web crawler example <web_crawler_example>`. Here's a tour of the interesting lines in this crawler. pool = eventlet.GreenPool()
for body in pool.imap(fetch, urls):
print("got body", len(body))
There is a slightly more complex version of this in the :ref:`web crawler example <web_crawler_example>`. Here's a tour of the interesting lines in this crawler.
``from eventlet.green import urllib2`` is how you import a cooperatively-yielding version of urllib2. It is the same in all respects to the standard version, except that it uses green sockets for its communication. This is an example of the :ref:`import-green` pattern. ``from eventlet.green import urllib2`` is how you import a cooperatively-yielding version of urllib2. It is the same in all respects to the standard version, except that it uses green sockets for its communication. This is an example of the :ref:`import-green` pattern.
@@ -40,15 +39,15 @@ Server Pattern
-------------------- --------------------
Here's a simple server-side example, a simple echo server:: Here's a simple server-side example, a simple echo server::
import eventlet import eventlet
def handle(client): def handle(client):
while True: while True:
c = client.recv(1) c = client.recv(1)
if not c: break if not c: break
client.sendall(c) client.sendall(c)
server = eventlet.listen(('0.0.0.0', 6000)) server = eventlet.listen(('0.0.0.0', 6000))
pool = eventlet.GreenPool(10000) pool = eventlet.GreenPool(10000)
while True: while True:
@@ -59,7 +58,7 @@ The file :ref:`echo server example <echo_server_example>` contains a somewhat mo
``server = eventlet.listen(('0.0.0.0', 6000))`` uses a convenience function to create a listening socket. ``server = eventlet.listen(('0.0.0.0', 6000))`` uses a convenience function to create a listening socket.
``pool = eventlet.GreenPool(10000)`` creates a pool of green threads that could handle ten thousand clients. ``pool = eventlet.GreenPool(10000)`` creates a pool of green threads that could handle ten thousand clients.
``pool.spawn_n(handle, new_sock)`` launches a green thread to handle the new client. The accept loop doesn't care about the return value of the ``handle`` function, so it uses :meth:`spawn_n <eventlet.greenpool.GreenPool.spawn_n>`, instead of :meth:`spawn <eventlet.greenpool.GreenPool.spawn>`. ``pool.spawn_n(handle, new_sock)`` launches a green thread to handle the new client. The accept loop doesn't care about the return value of the ``handle`` function, so it uses :meth:`spawn_n <eventlet.greenpool.GreenPool.spawn_n>`, instead of :meth:`spawn <eventlet.greenpool.GreenPool.spawn>`.
@@ -74,13 +73,13 @@ Here's a somewhat contrived example: a server that receives POSTs from clients t
import eventlet import eventlet
feedparser = eventlet.import_patched('feedparser') feedparser = eventlet.import_patched('feedparser')
pool = eventlet.GreenPool() pool = eventlet.GreenPool()
def fetch_title(url): def fetch_title(url):
d = feedparser.parse(url) d = feedparser.parse(url)
return d.feed.get('title', '') return d.feed.get('title', '')
def app(environ, start_response): def app(environ, start_response):
pile = eventlet.GreenPile(pool) pile = eventlet.GreenPile(pool)
for url in environ['wsgi.input'].readlines(): for url in environ['wsgi.input'].readlines():
@@ -110,4 +109,4 @@ Note that in line 1, the Pile is constructed using the global pool as its argume
Line 3 is just a spawn, but note that we don't store any return value from it. This is because the return value is kept in the Pile itself. This becomes evident in the next line... Line 3 is just a spawn, but note that we don't store any return value from it. This is because the return value is kept in the Pile itself. This becomes evident in the next line...
Line 4 is where we use the fact that the Pile is an iterator. Each element in the iterator is one of the return values from the fetch_title function, which are strings. We can use a normal Python idiom (:func:`join`) to concatenate these incrementally as they happen. Line 4 is where we use the fact that the Pile is an iterator. Each element in the iterator is one of the return values from the fetch_title function, which are strings. We can use a normal Python idiom (:func:`join`) to concatenate these incrementally as they happen.

View File

@@ -6,16 +6,16 @@ Code talks! This is a simple web crawler that fetches a bunch of urls concurren
urls = ["http://www.google.com/intl/en_ALL/images/logo.gif", urls = ["http://www.google.com/intl/en_ALL/images/logo.gif",
"https://wiki.secondlife.com/w/images/secondlife.jpg", "https://wiki.secondlife.com/w/images/secondlife.jpg",
"http://us.i1.yimg.com/us.yimg.com/i/ww/beta/y3.gif"] "http://us.i1.yimg.com/us.yimg.com/i/ww/beta/y3.gif"]
import eventlet import eventlet
from eventlet.green import urllib2 from eventlet.green import urllib2
def fetch(url): def fetch(url):
return urllib2.urlopen(url).read() return urllib2.urlopen(url).read()
pool = eventlet.GreenPool() pool = eventlet.GreenPool()
for body in pool.imap(fetch, urls): for body in pool.imap(fetch, urls):
print "got body", len(body) print("got body", len(body))
Contents Contents
========= =========
@@ -35,7 +35,7 @@ Contents
environment environment
modules modules
authors authors
history history

View File

@@ -1,7 +1,7 @@
:mod:`wsgi` -- WSGI server :mod:`wsgi` -- WSGI server
=========================== ===========================
The wsgi module provides a simple and easy way to start an event-driven The wsgi module provides a simple and easy way to start an event-driven
`WSGI <http://wsgi.org/wsgi/>`_ server. This can serve as an embedded `WSGI <http://wsgi.org/wsgi/>`_ server. This can serve as an embedded
web server in an application, or as the basis for a more full-featured web web server in an application, or as the basis for a more full-featured web
server package. One such package is `Spawning <http://pypi.python.org/pypi/Spawning/>`_. server package. One such package is `Spawning <http://pypi.python.org/pypi/Spawning/>`_.
@@ -10,11 +10,11 @@ To launch a wsgi server, simply create a socket and call :func:`eventlet.wsgi.se
from eventlet import wsgi from eventlet import wsgi
import eventlet import eventlet
def hello_world(env, start_response): def hello_world(env, start_response):
start_response('200 OK', [('Content-Type', 'text/plain')]) start_response('200 OK', [('Content-Type', 'text/plain')])
return ['Hello, World!\r\n'] return ['Hello, World!\r\n']
wsgi.server(eventlet.listen(('', 8090)), hello_world) wsgi.server(eventlet.listen(('', 8090)), hello_world)
@@ -55,14 +55,14 @@ For example::
import eventlet import eventlet
def hook(env, arg1, arg2, kwarg3=None, kwarg4=None): def hook(env, arg1, arg2, kwarg3=None, kwarg4=None):
print 'Hook called: %s %s %s %s %s' % (env, arg1, arg2, kwarg3, kwarg4) print('Hook called: %s %s %s %s %s' % (env, arg1, arg2, kwarg3, kwarg4))
def hello_world(env, start_response): def hello_world(env, start_response):
env['eventlet.posthooks'].append( env['eventlet.posthooks'].append(
(hook, ('arg1', 'arg2'), {'kwarg3': 3, 'kwarg4': 4})) (hook, ('arg1', 'arg2'), {'kwarg3': 3, 'kwarg4': 4}))
start_response('200 OK', [('Content-Type', 'text/plain')]) start_response('200 OK', [('Content-Type', 'text/plain')])
return ['Hello, World!\r\n'] return ['Hello, World!\r\n']
wsgi.server(eventlet.listen(('', 8090)), hello_world) wsgi.server(eventlet.listen(('', 8090)), hello_world)
The above code will print the WSGI environment and the other passed function The above code will print the WSGI environment and the other passed function

View File

@@ -131,7 +131,7 @@ def fetch(url):
pool = eventlet.GreenPool() pool = eventlet.GreenPool()
for body in pool.imap(fetch, urls): for body in pool.imap(fetch, urls):
print "got body", len(body) print("got body", len(body))
</code></pre> </code></pre>

View File

@@ -10,9 +10,9 @@ In either case, the the ``green`` modules handle SSL sockets transparently, just
bodies = [coros.execute(urllib2.urlopen, url) bodies = [coros.execute(urllib2.urlopen, url)
for url in ("https://secondlife.com","https://google.com")] for url in ("https://secondlife.com","https://google.com")]
for b in bodies: for b in bodies:
print b.wait().read() print(b.wait().read())
With Python 2.6 With Python 2.6
---------------- ----------------
@@ -34,7 +34,7 @@ Here's an example of a server::
from eventlet.green import socket from eventlet.green import socket
from eventlet.green.OpenSSL import SSL from eventlet.green.OpenSSL import SSL
# insecure context, only for example purposes # insecure context, only for example purposes
context = SSL.Context(SSL.SSLv23_METHOD) context = SSL.Context(SSL.SSLv23_METHOD)
context.set_verify(SSL.VERIFY_NONE, lambda *x: True)) context.set_verify(SSL.VERIFY_NONE, lambda *x: True))
@@ -42,15 +42,15 @@ Here's an example of a server::
# create underlying green socket and wrap it in ssl # create underlying green socket and wrap it in ssl
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connection = SSL.Connection(context, sock) connection = SSL.Connection(context, sock)
# configure as server # configure as server
connection.set_accept_state() connection.set_accept_state()
connection.bind(('127.0.0.1', 80443)) connection.bind(('127.0.0.1', 80443))
connection.listen(50) connection.listen(50)
# accept one client connection then close up shop # accept one client connection then close up shop
client_conn, addr = connection.accept() client_conn, addr = connection.accept()
print client_conn.read(100) print(client_conn.read(100))
client_conn.shutdown() client_conn.shutdown()
client_conn.close() client_conn.close()
connection.close() connection.close()

View File

@@ -1,7 +1,7 @@
Threads Threads
======== ========
Eventlet is thread-safe and can be used in conjunction with normal Python threads. The way this works is that coroutines are confined to their 'parent' Python thread. It's like each thread contains its own little world of coroutines that can switch between themselves but not between coroutines in other threads. Eventlet is thread-safe and can be used in conjunction with normal Python threads. The way this works is that coroutines are confined to their 'parent' Python thread. It's like each thread contains its own little world of coroutines that can switch between themselves but not between coroutines in other threads.
.. image:: /images/threading_illustration.png .. image:: /images/threading_illustration.png
@@ -19,7 +19,7 @@ The simplest thing to do with :mod:`~eventlet.tpool` is to :func:`~eventlet.tpoo
>>> import thread >>> import thread
>>> from eventlet import tpool >>> from eventlet import tpool
>>> def my_func(starting_ident): >>> def my_func(starting_ident):
... print "running in new thread:", starting_ident != thread.get_ident() ... print("running in new thread:", starting_ident != thread.get_ident())
... ...
>>> tpool.execute(my_func, thread.get_ident()) >>> tpool.execute(my_func, thread.get_ident())
running in new thread: True running in new thread: True

View File

@@ -129,11 +129,11 @@ class timeout(object):
an exception provided in *exc* argument will be raised an exception provided in *exc* argument will be raised
(:class:`~eventlet.api.TimeoutError` if *exc* is omitted):: (:class:`~eventlet.api.TimeoutError` if *exc* is omitted)::
try: try:
with timeout(10, MySpecialError, error_arg_1): with timeout(10, MySpecialError, error_arg_1):
urllib2.open('http://example.com') urllib2.open('http://example.com')
except MySpecialError as e: except MySpecialError as e:
print "special error received" print("special error received")
When *exc* is ``None``, code block is interrupted silently. When *exc* is ``None``, code block is interrupted silently.
""" """
@@ -194,7 +194,7 @@ def named(name):
obj = __import__(toimport) obj = __import__(toimport)
break break
except ImportError as err: except ImportError as err:
# print 'Import error on %s: %s' % (toimport, err) # debugging spam # print('Import error on %s: %s' % (toimport, err)) # debugging spam
import_err_strings.append(err.__str__()) import_err_strings.append(err.__str__())
toimport = '.'.join(toimport.split('.')[:-1]) toimport = '.'.join(toimport.split('.')[:-1])
if obj is None: if obj is None:
@@ -208,4 +208,3 @@ def named(name):
raise AttributeError('attribute %r missing from %r (%r) %r. Import errors: %r' % ( raise AttributeError('attribute %r missing from %r (%r) %r. Import errors: %r' % (
seg, obj, dirobj, name, import_err_strings)) seg, obj, dirobj, name, import_err_strings))
return obj return obj

View File

@@ -64,7 +64,7 @@ def serve(sock, handle, concurrency=1000):
two arguments: the client socket object, and the client address:: two arguments: the client socket object, and the client address::
def myhandle(client_sock, client_addr): def myhandle(client_sock, client_addr):
print "client connected", client_addr print("client connected", client_addr)
eventlet.serve(eventlet.listen(('127.0.0.1', 9999)), myhandle) eventlet.serve(eventlet.listen(('127.0.0.1', 9999)), myhandle)

View File

@@ -67,8 +67,8 @@ def select(read_list, write_list, error_list, timeout=None):
# at least once before timed out. otherwise the following code # at least once before timed out. otherwise the following code
# can time out erroneously. # can time out erroneously.
# #
# s1, s2 = socket.socketpair() # s1, s2 = socket.socketpair()
# print select.select([], [s1], [], 0) # print(select.select([], [s1], [], 0))
timers.append(hub.schedule_call_global(0, on_timeout2)) timers.append(hub.schedule_call_global(0, on_timeout2))
if timeout is not None: if timeout is not None:

View File

@@ -161,7 +161,7 @@ class GreenPool(object):
return do_something(line) return do_something(line)
pool = GreenPool() pool = GreenPool()
for result in pool.imap(worker, open("filename", 'r')): for result in pool.imap(worker, open("filename", 'r')):
print result print(result)
""" """
return self.starmap(function, six.moves.zip(*iterables)) return self.starmap(function, six.moves.zip(*iterables))

View File

@@ -22,7 +22,7 @@ class FirstSwitch(object):
self.gr = gr self.gr = gr
def __call__(self, *args, **kw): def __call__(self, *args, **kw):
#print "first call", args, kw #print("first call", args, kw)
gr = self.gr gr = self.gr
del gr.switch del gr.switch
run, gr.run = gr.run, None run, gr.run = gr.run, None
@@ -46,7 +46,7 @@ class greenlet(object):
self.switch = FirstSwitch(self) self.switch = FirstSwitch(self)
def switch(self, *args): def switch(self, *args):
#print "switch", args #print("switch", args)
global caller global caller
caller = stackless.getcurrent() caller = stackless.getcurrent()
coro_args[self] = args coro_args[self] = args

View File

@@ -53,11 +53,11 @@ assert highwater[0] > 20, "Highwater %%s <= %%s" %% (highwater[0], normal)
import eventlet import eventlet
import time import time
def do(): def do():
print "should not get here" print("should not get here")
try: try:
tpool.execute(do) tpool.execute(do)
except AssertionError: except AssertionError:
print "success" print("success")
""" """
os.environ['EVENTLET_THREADPOOL_SIZE'] = "-1" os.environ['EVENTLET_THREADPOOL_SIZE'] = "-1"
try: try:
@@ -73,7 +73,7 @@ except AssertionError:
import eventlet import eventlet
import time import time
def do(): def do():
print "ran it" print("ran it")
tpool.execute(do) tpool.execute(do)
""" """
os.environ['EVENTLET_THREADPOOL_SIZE'] = "0" os.environ['EVENTLET_THREADPOOL_SIZE'] = "0"
@@ -87,7 +87,6 @@ tpool.execute(do)
del os.environ['EVENTLET_THREADPOOL_SIZE'] del os.environ['EVENTLET_THREADPOOL_SIZE']
class Hub(ProcessBase): class Hub(ProcessBase):
def setUp(self): def setUp(self):
@@ -104,7 +103,7 @@ class Hub(ProcessBase):
def test_eventlet_hub(self): def test_eventlet_hub(self):
new_mod = """from eventlet import hubs new_mod = """from eventlet import hubs
print hubs.get_hub() print(hubs.get_hub())
""" """
self.write_to_tempfile("newmod", new_mod) self.write_to_tempfile("newmod", new_mod)
output, lines = self.launch_subprocess('newmod.py') output, lines = self.launch_subprocess('newmod.py')

View File

@@ -30,7 +30,7 @@ if (pid != 0):
break break
except (IOError, IndexError): except (IOError, IndexError):
eventlet.sleep(0.1) eventlet.sleep(0.1)
print 'result', result print('result {0}'.format(result))
finally: finally:
os.kill(pid, signal.SIGTERM) os.kill(pid, signal.SIGTERM)
else: else:

View File

@@ -267,7 +267,7 @@ eventlet.Timeout(0.5)
try: try:
eventlet.listen(("127.0.0.1", 0)).accept() eventlet.listen(("127.0.0.1", 0)).accept()
except eventlet.Timeout: except eventlet.Timeout:
print "exited correctly" print("exited correctly")
""") """)
fd.close() fd.close()
python_path = os.pathsep.join(sys.path + [self.tempdir]) python_path = os.pathsep.join(sys.path + [self.tempdir])
@@ -314,13 +314,13 @@ if not pid:
try: try:
new_sock, address = server.accept() new_sock, address = server.accept()
except eventlet.Timeout as t: except eventlet.Timeout as t:
print "accept blocked" print("accept blocked")
else: else:
kpid, status = os.wait() kpid, status = os.wait()
assert kpid == pid assert kpid == pid
assert status == 0 assert status == 0
print "child died ok" print("child died ok")
""" """
self.write_to_tempfile("newmod", new_mod) self.write_to_tempfile("newmod", new_mod)
output, lines = self.launch_subprocess('newmod.py') output, lines = self.launch_subprocess('newmod.py')

View File

@@ -1,10 +1,13 @@
from __future__ import print_function from __future__ import print_function
import os import os
import sys
import time import time
import traceback import traceback
from tests import skipped, skip_unless, using_pyevent, get_database_auth, LimitedTestCase from tests import (
LimitedTestCase,
run_python,
skip_unless, using_pyevent, get_database_auth,
)
import eventlet import eventlet
from eventlet import event from eventlet import event
try: try:
@@ -219,20 +222,16 @@ class MySQLdbTester(LimitedTestCase):
conn.commit() conn.commit()
from tests import patcher_test class TestMonkeyPatch(LimitedTestCase):
class MonkeyPatchTester(patcher_test.ProcessBase):
@skip_unless(mysql_requirement) @skip_unless(mysql_requirement)
def test_monkey_patching(self): def test_monkey_patching(self):
output, lines = self.run_script(""" testcode_path = os.path.join(
from eventlet import patcher os.path.dirname(os.path.abspath(__file__)),
import MySQLdb as m 'mysqldb_test_monkey_patch.py',
from eventlet.green import MySQLdb as gm )
patcher.monkey_patch(all=True, MySQLdb=True) output = run_python(testcode_path)
print "mysqltest", ",".join(sorted(patcher.already_patched.keys())) lines = output.splitlines()
print "connect", m.connect == gm.connect self.assertEqual(len(lines), 2, output)
""")
self.assertEqual(len(lines), 3)
self.assertEqual(lines[0].replace("psycopg,", ""), self.assertEqual(lines[0].replace("psycopg,", ""),
'mysqltest MySQLdb,os,select,socket,thread,time') 'mysqltest MySQLdb,os,select,socket,thread,time')
self.assertEqual(lines[1], "connect True") self.assertEqual(lines[1], "connect True")

View File

@@ -0,0 +1,12 @@
from __future__ import print_function
import MySQLdb as m
from eventlet import patcher
from eventlet.green import MySQLdb as gm
# no standard tests in this file, ignore
__test__ = False
if __name__ == '__main__':
patcher.monkey_patch(all=True, MySQLdb=True)
print("mysqltest {0}".format(",".join(sorted(patcher.already_patched.keys()))))
print("connect {0}".format(m.connect == gm.connect))

View File

@@ -11,7 +11,7 @@ import eventlet
eventlet.monkey_patch() eventlet.monkey_patch()
from eventlet import patcher from eventlet import patcher
if not patcher.is_monkey_patched('psycopg'): if not patcher.is_monkey_patched('psycopg'):
print "Psycopg not monkeypatched" print("Psycopg not monkeypatched")
sys.exit(0) sys.exit(0)
count = [0] count = [0]
@@ -32,7 +32,7 @@ f = eventlet.spawn(fetch, 2, 1)
t = eventlet.spawn(tick, 2, 100) t = eventlet.spawn(tick, 2, 100)
f.wait() f.wait()
assert count[0] > 100, count[0] assert count[0] > 100, count[0]
print "done" print("done")
""" """
class PatchingPsycopg(patcher_test.ProcessBase): class PatchingPsycopg(patcher_test.ProcessBase):

View File

@@ -10,14 +10,14 @@ from tests import LimitedTestCase, main, run_python, skip_with_pyevent
base_module_contents = """ base_module_contents = """
import socket import socket
import urllib import urllib
print "base", socket, urllib print("base {0} {1}".format(socket, urllib))
""" """
patching_module_contents = """ patching_module_contents = """
from eventlet.green import socket from eventlet.green import socket
from eventlet.green import urllib from eventlet.green import urllib
from eventlet import patcher from eventlet import patcher
print 'patcher', socket, urllib print('patcher {0} {1}'.format(socket, urllib))
patcher.inject('base', globals(), ('socket', socket), ('urllib', urllib)) patcher.inject('base', globals(), ('socket', socket), ('urllib', urllib))
del patcher del patcher
""" """
@@ -25,7 +25,7 @@ del patcher
import_module_contents = """ import_module_contents = """
import patching import patching
import socket import socket
print "importing", patching, socket, patching.socket, patching.urllib print("importing {0} {1} {2} {3}".format(patching, socket, patching.socket, patching.urllib))
""" """
@@ -83,7 +83,7 @@ class ImportPatched(ProcessBase):
new_mod = """ new_mod = """
from eventlet import patcher from eventlet import patcher
base = patcher.import_patched('base') base = patcher.import_patched('base')
print "newmod", base, base.socket, base.urllib.socket.socket print("newmod {0} {1} {2}".format(base, base.socket, base.urllib.socket.socket))
""" """
self.write_to_tempfile("newmod", new_mod) self.write_to_tempfile("newmod", new_mod)
output, lines = self.launch_subprocess('newmod.py') output, lines = self.launch_subprocess('newmod.py')
@@ -100,7 +100,7 @@ from eventlet import patcher
patcher.monkey_patch() patcher.monkey_patch()
import socket import socket
import urllib import urllib
print "newmod", socket.socket, urllib.socket.socket print("newmod {0} {1}".format(socket.socket, urllib.socket.socket))
""" """
self.write_to_tempfile("newmod", new_mod) self.write_to_tempfile("newmod", new_mod)
output, lines = self.launch_subprocess('newmod.py') output, lines = self.launch_subprocess('newmod.py')
@@ -113,7 +113,7 @@ from eventlet import patcher
patcher.monkey_patch() patcher.monkey_patch()
import eventlet import eventlet
eventlet.sleep(0.01) eventlet.sleep(0.01)
print "newmod" print("newmod")
""" """
self.write_to_tempfile("newmod", new_mod) self.write_to_tempfile("newmod", new_mod)
output, lines = self.launch_subprocess('newmod.py') output, lines = self.launch_subprocess('newmod.py')
@@ -127,7 +127,7 @@ eventlet.sleep(0.01)
from eventlet import patcher from eventlet import patcher
patcher.monkey_patch() patcher.monkey_patch()
eventlet.sleep(0.01) eventlet.sleep(0.01)
print "newmod" print("newmod")
""" """
self.write_to_tempfile("newmod", new_mod) self.write_to_tempfile("newmod", new_mod)
output, lines = self.launch_subprocess('newmod.py') output, lines = self.launch_subprocess('newmod.py')
@@ -156,7 +156,7 @@ for mod in [%s]:
assert patcher.is_monkey_patched(mod), mod assert patcher.is_monkey_patched(mod), mod
for mod in [%s]: for mod in [%s]:
assert not patcher.is_monkey_patched(mod), mod assert not patcher.is_monkey_patched(mod), mod
print "already_patched", ",".join(sorted(patcher.already_patched.keys())) print("already_patched {0}".format(",".join(sorted(patcher.already_patched.keys()))))
""" % (call, expected_list, not_expected_list) """ % (call, expected_list, not_expected_list)
self.write_to_tempfile("newmod", new_mod) self.write_to_tempfile("newmod", new_mod)
output, lines = self.launch_subprocess('newmod.py') output, lines = self.launch_subprocess('newmod.py')
@@ -227,7 +227,7 @@ def test_monkey_patch_threading():
eventlet.spawn(tick) eventlet.spawn(tick)
w1 = eventlet.spawn(do_sleep) w1 = eventlet.spawn(do_sleep)
w1.wait() w1.wait()
print tickcount[0] print(tickcount[0])
assert tickcount[0] > 900 assert tickcount[0] > 900
tpool.killall() tpool.killall()
""" """
@@ -242,8 +242,8 @@ import eventlet
from eventlet import patcher from eventlet import patcher
patcher.monkey_patch() patcher.monkey_patch()
from eventlet import tpool from eventlet import tpool
print "newmod", tpool.execute(len, "hi") print("newmod {0}".format(tpool.execute(len, "hi")))
print "newmod", tpool.execute(len, "hi2") print("newmod {0}".format(tpool.execute(len, "hi2")))
tpool.killall() tpool.killall()
""" """
self.write_to_tempfile("newmod", new_mod) self.write_to_tempfile("newmod", new_mod)
@@ -287,7 +287,7 @@ eventlet.monkey_patch()
from eventlet.green import subprocess from eventlet.green import subprocess
subprocess.Popen(['true'], stdin=subprocess.PIPE) subprocess.Popen(['true'], stdin=subprocess.PIPE)
print "done" print("done")
""" """
self.write_to_tempfile("newmod", new_mod) self.write_to_tempfile("newmod", new_mod)
output, lines = self.launch_subprocess('newmod') output, lines = self.launch_subprocess('newmod')
@@ -302,12 +302,12 @@ from eventlet import patcher
import threading import threading
_threading = patcher.original('threading') _threading = patcher.original('threading')
def test(): def test():
print repr(threading.currentThread()) print(repr(threading.currentThread()))
t = _threading.Thread(target=test) t = _threading.Thread(target=test)
t.start() t.start()
t.join() t.join()
print len(threading._active) print(len(threading._active))
print len(_threading._active) print(len(_threading._active))
""" """
self.write_to_tempfile("newmod", new_mod) self.write_to_tempfile("newmod", new_mod)
output, lines = self.launch_subprocess('newmod') output, lines = self.launch_subprocess('newmod')
@@ -321,11 +321,11 @@ print len(_threading._active)
eventlet.monkey_patch() eventlet.monkey_patch()
import threading import threading
def test(): def test():
print repr(threading.currentThread()) print(repr(threading.currentThread()))
t = threading.Thread(target=test) t = threading.Thread(target=test)
t.start() t.start()
t.join() t.join()
print len(threading._active) print(len(threading._active))
""" """
self.write_to_tempfile("newmod", new_mod) self.write_to_tempfile("newmod", new_mod)
output, lines = self.launch_subprocess('newmod') output, lines = self.launch_subprocess('newmod')
@@ -339,9 +339,9 @@ eventlet.monkey_patch()
from eventlet import tpool from eventlet import tpool
import threading import threading
def test(): def test():
print repr(threading.currentThread()) print(repr(threading.currentThread()))
tpool.execute(test) tpool.execute(test)
print len(threading._active) print(len(threading._active))
""" """
self.write_to_tempfile("newmod", new_mod) self.write_to_tempfile("newmod", new_mod)
output, lines = self.launch_subprocess('newmod') output, lines = self.launch_subprocess('newmod')
@@ -356,11 +356,11 @@ from eventlet import event
import threading import threading
evt = event.Event() evt = event.Event()
def test(): def test():
print repr(threading.currentThread()) print(repr(threading.currentThread()))
evt.send() evt.send()
eventlet.spawn_n(test) eventlet.spawn_n(test)
evt.wait() evt.wait()
print len(threading._active) print(len(threading._active))
""" """
self.write_to_tempfile("newmod", new_mod) self.write_to_tempfile("newmod", new_mod)
output, lines = self.launch_subprocess('newmod') output, lines = self.launch_subprocess('newmod')
@@ -373,10 +373,10 @@ print len(threading._active)
eventlet.monkey_patch() eventlet.monkey_patch()
import threading import threading
def test(): def test():
print repr(threading.currentThread()) print(repr(threading.currentThread()))
t = eventlet.spawn(test) t = eventlet.spawn(test)
t.wait() t.wait()
print len(threading._active) print(len(threading._active))
""" """
self.write_to_tempfile("newmod", new_mod) self.write_to_tempfile("newmod", new_mod)
output, lines = self.launch_subprocess('newmod') output, lines = self.launch_subprocess('newmod')
@@ -399,7 +399,7 @@ class Os(ProcessBase):
import eventlet import eventlet
eventlet.monkey_patch(all=False, os=True) eventlet.monkey_patch(all=False, os=True)
process = subprocess.Popen("sleep 0.1 && false", shell=True) process = subprocess.Popen("sleep 0.1 && false", shell=True)
print process.wait()""" print(process.wait())"""
self.write_to_tempfile("newmod", new_mod) self.write_to_tempfile("newmod", new_mod)
output, lines = self.launch_subprocess('newmod') output, lines = self.launch_subprocess('newmod')
self.assertEqual(len(lines), 2, "\n".join(lines)) self.assertEqual(len(lines), 2, "\n".join(lines))
@@ -425,7 +425,7 @@ t.wait()
t2 = threading.currentThread() t2 = threading.currentThread()
eventlet.spawn(test2) eventlet.spawn(test2)
""" + self.epilogue + """ """ + self.epilogue + """
print repr(t2) print(repr(t2))
t2.join() t2.join()
""") """)
output, lines = self.launch_subprocess('newmod') output, lines = self.launch_subprocess('newmod')
@@ -434,17 +434,17 @@ t2.join()
def test_name(self): def test_name(self):
self.write_to_tempfile("newmod", self.prologue + """ self.write_to_tempfile("newmod", self.prologue + """
print t.name print(t.name)
print t.getName() print(t.getName())
print t.get_name() print(t.get_name())
t.name = 'foo' t.name = 'foo'
print t.name print(t.name)
print t.getName() print(t.getName())
print t.get_name() print(t.get_name())
t.setName('bar') t.setName('bar')
print t.name print(t.name)
print t.getName() print(t.getName())
print t.get_name() print(t.get_name())
""" + self.epilogue) """ + self.epilogue)
output, lines = self.launch_subprocess('newmod') output, lines = self.launch_subprocess('newmod')
self.assertEqual(len(lines), 10, "\n".join(lines)) self.assertEqual(len(lines), 10, "\n".join(lines))
@@ -457,8 +457,8 @@ t2.join()
def test_ident(self): def test_ident(self):
self.write_to_tempfile("newmod", self.prologue + """ self.write_to_tempfile("newmod", self.prologue + """
print id(t._g) print(id(t._g))
print t.ident print(t.ident)
""" + self.epilogue) """ + self.epilogue)
output, lines = self.launch_subprocess('newmod') output, lines = self.launch_subprocess('newmod')
self.assertEqual(len(lines), 3, "\n".join(lines)) self.assertEqual(len(lines), 3, "\n".join(lines))
@@ -466,8 +466,8 @@ t2.join()
def test_is_alive(self): def test_is_alive(self):
self.write_to_tempfile("newmod", self.prologue + """ self.write_to_tempfile("newmod", self.prologue + """
print t.is_alive() print(t.is_alive())
print t.isAlive() print(t.isAlive())
""" + self.epilogue) """ + self.epilogue)
output, lines = self.launch_subprocess('newmod') output, lines = self.launch_subprocess('newmod')
self.assertEqual(len(lines), 3, "\n".join(lines)) self.assertEqual(len(lines), 3, "\n".join(lines))
@@ -476,8 +476,8 @@ t2.join()
def test_is_daemon(self): def test_is_daemon(self):
self.write_to_tempfile("newmod", self.prologue + """ self.write_to_tempfile("newmod", self.prologue + """
print t.is_daemon() print(t.is_daemon())
print t.isDaemon() print(t.isDaemon())
""" + self.epilogue) """ + self.epilogue)
output, lines = self.launch_subprocess('newmod') output, lines = self.launch_subprocess('newmod')
self.assertEqual(len(lines), 3, "\n".join(lines)) self.assertEqual(len(lines), 3, "\n".join(lines))

View File

@@ -15,7 +15,7 @@ def start_http_server():
server_address = ('localhost', 0) server_address = ('localhost', 0)
httpd = BaseHTTPServer.HTTPServer(server_address, QuietHandler) httpd = BaseHTTPServer.HTTPServer(server_address, QuietHandler)
sa = httpd.socket.getsockname() sa = httpd.socket.getsockname()
#print "Serving HTTP on", sa[0], "port", sa[1], "..." #print("Serving HTTP on", sa[0], "port", sa[1], "...")
httpd.request_count = 0 httpd.request_count = 0
def serve(): def serve():
# increment the request_count before handling the request because # increment the request_count before handling the request because
@@ -28,7 +28,7 @@ class TestGreenness(unittest.TestCase):
def setUp(self): def setUp(self):
self.gthread, self.server,self.port = start_http_server() self.gthread, self.server,self.port = start_http_server()
#print 'Spawned the server' #print('Spawned the server')
def tearDown(self): def tearDown(self):
self.server.server_close() self.server.server_close()

View File

@@ -29,25 +29,26 @@ def handle_request(s, raise_on_timeout):
raise raise
else: else:
return return
#print 'handle_request - accepted' #print('handle_request - accepted')
res = conn.recv(100) res = conn.recv(100)
assert res == 'hello', repr(res) assert res == 'hello', repr(res)
#print 'handle_request - recvd %r' % res #print('handle_request - recvd %r' % res)
res = conn.send('bye') res = conn.send('bye')
#print 'handle_request - sent %r' % res #print('handle_request - sent %r' % res)
#print 'handle_request - conn refcount: %s' % sys.getrefcount(conn) #print('handle_request - conn refcount: %s' % sys.getrefcount(conn))
#conn.close() #conn.close()
def make_request(port): def make_request(port):
#print 'make_request' #print('make_request')
s = socket.socket() s = socket.socket()
s.connect(('localhost', port)) s.connect(('localhost', port))
#print 'make_request - connected' #print('make_request - connected')
res = s.send('hello') res = s.send('hello')
#print 'make_request - sent %s' % res #print('make_request - sent %s' % res)
res = s.recv(100) res = s.recv(100)
assert res == 'bye', repr(res) assert res == 'bye', repr(res)
#print 'make_request - recvd %r' % res #print('make_request - recvd %r' % res)
#s.close() #s.close()
def run_interaction(run_client): def run_interaction(run_client):
@@ -56,7 +57,7 @@ def run_interaction(run_client):
if run_client: if run_client:
start_new_thread(make_request, (port,)) start_new_thread(make_request, (port,))
sleep(0.1+SOCKET_TIMEOUT) sleep(0.1+SOCKET_TIMEOUT)
#print sys.getrefcount(s.fd) #print(sys.getrefcount(s.fd))
#s.close() #s.close()
return weakref.ref(s.fd) return weakref.ref(s.fd)