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,20 +10,19 @@ 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::
import eventlet
from eventlet.green import urllib2
urls = ["http://www.google.com/intl/en_ALL/images/logo.gif",
"https://wiki.secondlife.com/w/images/secondlife.jpg",
"http://us.i1.yimg.com/us.yimg.com/i/ww/beta/y3.gif"]
urls = ["http://www.google.com/intl/en_ALL/images/logo.gif",
"https://wiki.secondlife.com/w/images/secondlife.jpg",
"http://us.i1.yimg.com/us.yimg.com/i/ww/beta/y3.gif"]
import eventlet
from eventlet.green import urllib2
def fetch(url):
return urllib2.urlopen(url).read()
def fetch(url):
return urllib2.urlopen(url).read()
pool = eventlet.GreenPool()
for body in pool.imap(fetch, urls):
print "got body", len(body)
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.

View File

@@ -15,7 +15,7 @@ Code talks! This is a simple web crawler that fetches a bunch of urls concurren
pool = eventlet.GreenPool()
for body in pool.imap(fetch, urls):
print "got body", len(body)
print("got body", len(body))
Contents
=========

View File

@@ -55,7 +55,7 @@ For example::
import eventlet
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):
env['eventlet.posthooks'].append(

View File

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

View File

@@ -10,7 +10,7 @@ In either case, the the ``green`` modules handle SSL sockets transparently, just
bodies = [coros.execute(urllib2.urlopen, url)
for url in ("https://secondlife.com","https://google.com")]
for b in bodies:
print b.wait().read()
print(b.wait().read())
With Python 2.6
@@ -50,7 +50,7 @@ Here's an example of a server::
# accept one client connection then close up shop
client_conn, addr = connection.accept()
print client_conn.read(100)
print(client_conn.read(100))
client_conn.shutdown()
client_conn.close()
connection.close()

View File

@@ -19,7 +19,7 @@ The simplest thing to do with :mod:`~eventlet.tpool` is to :func:`~eventlet.tpoo
>>> import thread
>>> from eventlet import tpool
>>> 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())
running in new thread: True

View File

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

View File

@@ -64,7 +64,7 @@ def serve(sock, handle, concurrency=1000):
two arguments: the client socket object, and the client address::
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)

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
# can time out erroneously.
#
# s1, s2 = socket.socketpair()
# print select.select([], [s1], [], 0)
# s1, s2 = socket.socketpair()
# print(select.select([], [s1], [], 0))
timers.append(hub.schedule_call_global(0, on_timeout2))
if timeout is not None:

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,10 +1,13 @@
from __future__ import print_function
import os
import sys
import time
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
from eventlet import event
try:
@@ -219,20 +222,16 @@ class MySQLdbTester(LimitedTestCase):
conn.commit()
from tests import patcher_test
class MonkeyPatchTester(patcher_test.ProcessBase):
class TestMonkeyPatch(LimitedTestCase):
@skip_unless(mysql_requirement)
def test_monkey_patching(self):
output, lines = self.run_script("""
from eventlet import patcher
import MySQLdb as m
from eventlet.green import MySQLdb as gm
patcher.monkey_patch(all=True, MySQLdb=True)
print "mysqltest", ",".join(sorted(patcher.already_patched.keys()))
print "connect", m.connect == gm.connect
""")
self.assertEqual(len(lines), 3)
testcode_path = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
'mysqldb_test_monkey_patch.py',
)
output = run_python(testcode_path)
lines = output.splitlines()
self.assertEqual(len(lines), 2, output)
self.assertEqual(lines[0].replace("psycopg,", ""),
'mysqltest MySQLdb,os,select,socket,thread,time')
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()
from eventlet import patcher
if not patcher.is_monkey_patched('psycopg'):
print "Psycopg not monkeypatched"
print("Psycopg not monkeypatched")
sys.exit(0)
count = [0]
@@ -32,7 +32,7 @@ f = eventlet.spawn(fetch, 2, 1)
t = eventlet.spawn(tick, 2, 100)
f.wait()
assert count[0] > 100, count[0]
print "done"
print("done")
"""
class PatchingPsycopg(patcher_test.ProcessBase):

View File

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

View File

@@ -15,7 +15,7 @@ def start_http_server():
server_address = ('localhost', 0)
httpd = BaseHTTPServer.HTTPServer(server_address, QuietHandler)
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
def serve():
# increment the request_count before handling the request because
@@ -28,7 +28,7 @@ class TestGreenness(unittest.TestCase):
def setUp(self):
self.gthread, self.server,self.port = start_http_server()
#print 'Spawned the server'
#print('Spawned the server')
def tearDown(self):
self.server.server_close()

View File

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