Commit 08570bf3 authored by Fantix King's avatar Fantix King Committed by Denis Bilenko

Replaced print with print_function from __future__, refs #38.

parent c412d47a
...@@ -49,7 +49,7 @@ travistest: ...@@ -49,7 +49,7 @@ travistest:
${PYTHON} --version ${PYTHON} --version
cd greenlet-* && ${PYTHON} setup.py install -q cd greenlet-* && ${PYTHON} setup.py install -q
${PYTHON} -c 'import greenlet; print (greenlet, greenlet.__version__)' ${PYTHON} -c 'import greenlet; print(greenlet, greenlet.__version__)'
${PYTHON} setup.py install ${PYTHON} setup.py install
...@@ -75,7 +75,7 @@ travis: ...@@ -75,7 +75,7 @@ travis:
pip install -q --download . greenlet pip install -q --download . greenlet
unzip -q greenlet-*.zip unzip -q greenlet-*.zip
ack -w subprocess greentest/ -l -v | python -c 'import sys; print "\n".join(line.split("/")[-1].strip() for line in sys.stdin)' > greentest/tests_that_dont_use_subprocess.txt ack -w subprocess greentest/ -l -v | python -c 'import sys; print("\n".join(line.split("/")[-1].strip() for line in sys.stdin))' > greentest/tests_that_dont_use_subprocess.txt
sudo -E make travistest sudo -E make travistest
......
#!/bin/sh #!/bin/sh
set -e -x set -e -x
python -c 'import gevent.core; print gevent.__version__, gevent.core.get_version(), getattr(gevent.core, "get_method", lambda: "n/a")(), getattr(gevent, "get_hub", lambda: "n/a")()' python -c 'import gevent.core; from __future__ import print_function; print(gevent.__version__, gevent.core.get_version(), getattr(gevent.core, "get_method", lambda: "n/a")(), getattr(gevent, "get_hub", lambda: "n/a")())'
python -mtimeit -r 6 -s'obj = Exception(); obj.x=5' 'obj.x' python -mtimeit -r 6 -s'obj = Exception(); obj.x=5' 'obj.x'
python -mtimeit -r 6 -s'from gevent import get_hub; get_hub()' 'get_hub()' python -mtimeit -r 6 -s'from gevent import get_hub; get_hub()' 'get_hub()'
python -mtimeit -r 6 -s'from gevent import getcurrent' 'getcurrent()' python -mtimeit -r 6 -s'from gevent import getcurrent' 'getcurrent()'
......
...@@ -11,6 +11,7 @@ ...@@ -11,6 +11,7 @@
# All configuration values have a default; values that are commented out # All configuration values have a default; values that are commented out
# serve to show the default. # serve to show the default.
from __future__ import print_function
import sys import sys
import os import os
...@@ -19,7 +20,7 @@ os.system('%s generate_rst.py generate' % sys.executable) ...@@ -19,7 +20,7 @@ os.system('%s generate_rst.py generate' % sys.executable)
sys.path.append('.') # for mysphinxext sys.path.append('.') # for mysphinxext
if not os.path.exists('changelog.rst') and os.path.exists('../changelog.rst'): if not os.path.exists('changelog.rst') and os.path.exists('../changelog.rst'):
print 'Linking ../changelog.rst to changelog.rst' print('Linking ../changelog.rst to changelog.rst')
if hasattr(os, 'symlink'): if hasattr(os, 'symlink'):
os.symlink('../changelog.rst', 'changelog.rst') os.symlink('../changelog.rst', 'changelog.rst')
else: else:
......
#!/usr/bin/env python #!/usr/bin/env python
from __future__ import print_function
import os import os
import glob import glob
from os.path import join, dirname, abspath, basename from os.path import join, dirname, abspath, basename
...@@ -21,7 +22,7 @@ template = '''.. AUTOGENERATED -- will be overwritten (remove this comment to sa ...@@ -21,7 +22,7 @@ template = '''.. AUTOGENERATED -- will be overwritten (remove this comment to sa
''' '''
directory = dirname(abspath(gevent.__file__)) directory = dirname(abspath(gevent.__file__))
print 'Imported gevent from %s' % (directory, ) print('Imported gevent from %s' % (directory, ))
modules = glob.glob(join(directory, '*.py')) + glob.glob(join(directory, '*.pyc')) modules = glob.glob(join(directory, '*.py')) + glob.glob(join(directory, '*.pyc'))
modules = set(basename(filename).split('.')[0] for filename in modules) modules = set(basename(filename).split('.')[0] for filename in modules)
modules = set(name for name in modules if not name.startswith('_')) modules = set(name for name in modules if not name.startswith('_'))
...@@ -56,10 +57,10 @@ def generate_rst_for_module(module, do=True): ...@@ -56,10 +57,10 @@ def generate_rst_for_module(module, do=True):
if open(rst_filename).read(len(result) + 1) == result: if open(rst_filename).read(len(result) + 1) == result:
return # already exists one which is the same return # already exists one which is the same
if do: if do:
print 'Generated %s from %s' % (rst_filename, m.__file__) print('Generated %s from %s' % (rst_filename, m.__file__))
open(rst_filename, 'w').write(result) open(rst_filename, 'w').write(result)
else: else:
print 'Would generate %s from %s' % (rst_filename, m.__file__) print('Would generate %s from %s' % (rst_filename, m.__file__))
def generate_rst(do=True): def generate_rst(do=True):
...@@ -83,10 +84,10 @@ if __name__ == '__main__': ...@@ -83,10 +84,10 @@ if __name__ == '__main__':
import sys import sys
if sys.argv[1:] == ['show']: if sys.argv[1:] == ['show']:
for filename in iter_autogenerated(): for filename in iter_autogenerated():
print filename print(filename)
elif sys.argv[1:] == ['delete']: elif sys.argv[1:] == ['delete']:
for filename in iter_autogenerated(): for filename in iter_autogenerated():
print 'Removing', filename print('Removing', filename)
os.unlink(filename) os.unlink(filename)
elif sys.argv[1:] == ['generate']: elif sys.argv[1:] == ['generate']:
generate_rst() generate_rst()
......
from __future__ import print_function
from sphinx.ext.autodoc import cut_lines from sphinx.ext.autodoc import cut_lines
from sphinx.ext import intersphinx from sphinx.ext import intersphinx
from docutils import nodes from docutils import nodes
...@@ -34,20 +35,20 @@ def missing_reference(app, env, node, contnode): ...@@ -34,20 +35,20 @@ def missing_reference(app, env, node, contnode):
newnode.append(contnode) newnode.append(contnode)
msg = 'Resolved missing-reference: :%5s:`%s` -> %s' % (type, target, refuri) msg = 'Resolved missing-reference: :%5s:`%s` -> %s' % (type, target, refuri)
if noisy >= 1 or msg not in message_cache: if noisy >= 1 or msg not in message_cache:
print msg print(msg)
message_cache.add(msg) message_cache.add(msg)
return newnode return newnode
if noisy >= 1: if noisy >= 1:
print 'Looking for %s' % [type, target, modname, classname] print('Looking for %s' % [type, target, modname, classname])
print node print(node)
for docname, items in env.indexentries.iteritems(): for docname, items in env.indexentries.iteritems():
if noisy >= 2: if noisy >= 2:
print docname print(docname)
for (i_type, i_string, i_target, i_aliasname) in items: for (i_type, i_string, i_target, i_aliasname) in items:
if noisy >= 3: if noisy >= 3:
print '---', [i_type, i_string, i_target, i_aliasname] print('---', [i_type, i_string, i_target, i_aliasname])
if i_aliasname.endswith(target): if i_aliasname.endswith(target):
stripped_aliasname = i_aliasname[len(docname):] stripped_aliasname = i_aliasname[len(docname):]
if stripped_aliasname: if stripped_aliasname:
...@@ -55,7 +56,7 @@ def missing_reference(app, env, node, contnode): ...@@ -55,7 +56,7 @@ def missing_reference(app, env, node, contnode):
stripped_aliasname = stripped_aliasname[1:] stripped_aliasname = stripped_aliasname[1:]
if stripped_aliasname == target: if stripped_aliasname == target:
if noisy >= 1: if noisy >= 1:
print '--- found %s %s in %s' % (type, target, i_aliasname) print('--- found %s %s in %s' % (type, target, i_aliasname))
return new_reference(docname + '.html#' + i_aliasname, i_aliasname) return new_reference(docname + '.html#' + i_aliasname, i_aliasname)
if type == 'mod': if type == 'mod':
......
...@@ -7,7 +7,7 @@ Implementing servers ...@@ -7,7 +7,7 @@ Implementing servers
There are a few classes to simplify server implementation with gevent. They all share the similar interface:: There are a few classes to simplify server implementation with gevent. They all share the similar interface::
def handle(socket, address): def handle(socket, address):
print 'new connection!' print('new connection!')
server = StreamServer(('127.0.0.1', 1234), handle) # creates a new server server = StreamServer(('127.0.0.1', 1234), handle) # creates a new server
server.start() # start accepting new connections server.start() # start accepting new connections
......
...@@ -2,6 +2,7 @@ ...@@ -2,6 +2,7 @@
# Copyright (c) 2009 Denis Bilenko. See LICENSE for details. # Copyright (c) 2009 Denis Bilenko. See LICENSE for details.
"""Spawn multiple workers and wait for them to complete""" """Spawn multiple workers and wait for them to complete"""
from __future__ import print_function
urls = ['http://www.google.com', 'http://www.yandex.ru', 'http://www.python.org'] urls = ['http://www.google.com', 'http://www.yandex.ru', 'http://www.python.org']
...@@ -15,9 +16,9 @@ import urllib2 ...@@ -15,9 +16,9 @@ import urllib2
def print_head(url): def print_head(url):
print ('Starting %s' % url) print('Starting %s' % url)
data = urllib2.urlopen(url).read() data = urllib2.urlopen(url).read()
print ('%s: %s bytes: %r' % (url, len(data), data[:50])) print('%s: %s bytes: %r' % (url, len(data), data[:50]))
jobs = [gevent.spawn(print_head, url) for url in urls] jobs = [gevent.spawn(print_head, url) for url in urls]
......
...@@ -9,6 +9,7 @@ variable. To enable threading resolver: ...@@ -9,6 +9,7 @@ variable. To enable threading resolver:
GEVENT_RESOLVER=thread python dns_mass_resolve.py GEVENT_RESOLVER=thread python dns_mass_resolve.py
""" """
from __future__ import print_function
from __future__ import with_statement from __future__ import with_statement
import gevent import gevent
from gevent import socket from gevent import socket
...@@ -25,9 +26,9 @@ def job(url): ...@@ -25,9 +26,9 @@ def job(url):
try: try:
try: try:
ip = socket.gethostbyname(url) ip = socket.gethostbyname(url)
print ('%s = %s' % (url, ip)) print('%s = %s' % (url, ip))
except socket.gaierror as ex: except socket.gaierror as ex:
print ('%s failed with %s' % (url, ex)) print('%s failed with %s' % (url, ex))
finally: finally:
finished += 1 finished += 1
...@@ -36,4 +37,4 @@ with gevent.Timeout(2, False): ...@@ -36,4 +37,4 @@ with gevent.Timeout(2, False):
pool.spawn(job, '%s.com' % x) pool.spawn(job, '%s.com' % x)
pool.join() pool.join()
print ('finished within 2 seconds: %s/%s' % (finished, N)) print('finished within 2 seconds: %s/%s' % (finished, N))
...@@ -6,26 +6,27 @@ Connect to it with: ...@@ -6,26 +6,27 @@ Connect to it with:
Terminate the connection by terminating telnet (typically Ctrl-] and then 'quit'). Terminate the connection by terminating telnet (typically Ctrl-] and then 'quit').
""" """
from __future__ import print_function
from gevent.server import StreamServer from gevent.server import StreamServer
# this handler will be run for each incoming connection in a dedicated greenlet # this handler will be run for each incoming connection in a dedicated greenlet
def echo(socket, address): def echo(socket, address):
print ('New connection from %s:%s' % address) print('New connection from %s:%s' % address)
socket.sendall('Welcome to the echo server! Type quit to exit.\r\n') socket.sendall('Welcome to the echo server! Type quit to exit.\r\n')
# using a makefile because we want to use readline() # using a makefile because we want to use readline()
fileobj = socket.makefile() fileobj = socket.makefile()
while True: while True:
line = fileobj.readline() line = fileobj.readline()
if not line: if not line:
print ("client disconnected") print("client disconnected")
break break
if line.strip().lower() == 'quit': if line.strip().lower() == 'quit':
print ("client quit") print("client quit")
break break
fileobj.write(line) fileobj.write(line)
fileobj.flush() fileobj.flush()
print ("echoed %r" % line) print("echoed %r" % line)
if __name__ == '__main__': if __name__ == '__main__':
...@@ -33,5 +34,5 @@ if __name__ == '__main__': ...@@ -33,5 +34,5 @@ if __name__ == '__main__':
server = StreamServer(('0.0.0.0', 6000), echo) server = StreamServer(('0.0.0.0', 6000), echo)
# to start the server asynchronously, use its start() method; # to start the server asynchronously, use its start() method;
# we use blocking serve_forever() here because we have no other jobs # we use blocking serve_forever() here because we have no other jobs
print ('Starting echo server on port 6000') print('Starting echo server on port 6000')
server.serve_forever() server.serve_forever()
...@@ -12,7 +12,7 @@ def gevent_sendfile(out_fd, in_fd, offset, count): ...@@ -12,7 +12,7 @@ def gevent_sendfile(out_fd, in_fd, offset, count):
while total_sent < count: while total_sent < count:
try: try:
_offset, sent = original_sendfile(out_fd, in_fd, offset + total_sent, count - total_sent) _offset, sent = original_sendfile(out_fd, in_fd, offset + total_sent, count - total_sent)
#print '%s: sent %s [%d%%]' % (out_fd, sent, 100*total_sent/count) #print('%s: sent %s [%d%%]' % (out_fd, sent, 100*total_sent/count))
total_sent += sent total_sent += sent
except OSError as ex: except OSError as ex:
if ex[0] == EAGAIN: if ex[0] == EAGAIN:
......
#!/usr/bin/env python #!/usr/bin/env python
from __future__ import print_function
import gevent import gevent
from gevent import subprocess from gevent import subprocess
...@@ -11,10 +12,10 @@ gevent.wait([p1, p2], timeout=2) ...@@ -11,10 +12,10 @@ gevent.wait([p1, p2], timeout=2)
# print the results (if available) # print the results (if available)
if p1.poll() is not None: if p1.poll() is not None:
print ('uname: %r' % p1.stdout.read()) print('uname: %r' % p1.stdout.read())
else: else:
print ('uname: job is still running') print('uname: job is still running')
if p2.poll() is not None: if p2.poll() is not None:
print ('ls: %r' % p2.stdout.read()) print('ls: %r' % p2.stdout.read())
else: else:
print ('ls: job is still running') print('ls: job is still running')
from __future__ import print_function
from __future__ import with_statement from __future__ import with_statement
import sys import sys
import contextlib import contextlib
...@@ -153,4 +154,4 @@ if __name__ == '__main__': ...@@ -153,4 +154,4 @@ if __name__ == '__main__':
gevent.spawn(pool.execute, 'select pg_sleep(1);') gevent.spawn(pool.execute, 'select pg_sleep(1);')
gevent.wait() gevent.wait()
delay = time.time() - start delay = time.time() - start
print 'Running "select pg_sleep(1);" 4 times with 3 connections. Should take about 2 seconds: %.2fs' % delay print('Running "select pg_sleep(1);" 4 times with 3 connections. Should take about 2 seconds: %.2fs' % delay)
from __future__ import print_function
import time import time
import gevent import gevent
from gevent.threadpool import ThreadPool from gevent.threadpool import ThreadPool
...@@ -9,4 +10,4 @@ for _ in range(4): ...@@ -9,4 +10,4 @@ for _ in range(4):
pool.spawn(time.sleep, 1) pool.spawn(time.sleep, 1)
gevent.wait() gevent.wait()
delay = time.time() - start delay = time.time() - start
print 'Running "time.sleep(1)" 4 times with 3 threads. Should take about 2 seconds: %.3fs' % delay print('Running "time.sleep(1)" 4 times with 3 threads. Should take about 2 seconds: %.3fs' % delay)
...@@ -7,6 +7,7 @@ Make sure you're running a UDP server on port 9000 (see udp_server.py). ...@@ -7,6 +7,7 @@ Make sure you're running a UDP server on port 9000 (see udp_server.py).
There's nothing gevent-specific here. There's nothing gevent-specific here.
""" """
from __future__ import print_function
import sys import sys
from gevent import socket from gevent import socket
...@@ -14,7 +15,7 @@ address = ('localhost', 9000) ...@@ -14,7 +15,7 @@ address = ('localhost', 9000)
message = ' '.join(sys.argv[1:]) message = ' '.join(sys.argv[1:])
sock = socket.socket(type=socket.SOCK_DGRAM) sock = socket.socket(type=socket.SOCK_DGRAM)
sock.connect(address) sock.connect(address)
print 'Sending %s bytes to %s:%s' % ((len(message), ) + address) print('Sending %s bytes to %s:%s' % ((len(message), ) + address))
sock.send(message) sock.send(message)
data, address = sock.recvfrom(8192) data, address = sock.recvfrom(8192)
print '%s:%s: got %r' % (address + (data, )) print('%s:%s: got %r' % (address + (data, )))
...@@ -5,16 +5,17 @@ For every message received, it sends a reply back. ...@@ -5,16 +5,17 @@ For every message received, it sends a reply back.
You can use udp_client.py to send a message. You can use udp_client.py to send a message.
""" """
from __future__ import print_function
from gevent.server import DatagramServer from gevent.server import DatagramServer
class EchoServer(DatagramServer): class EchoServer(DatagramServer):
def handle(self, data, address): def handle(self, data, address):
print '%s: got %r' % (address[0], data) print('%s: got %r' % (address[0], data))
self.socket.sendto('Received %s bytes' % len(data), address) self.socket.sendto('Received %s bytes' % len(data), address)
if __name__ == '__main__': if __name__ == '__main__':
print 'Receiving datagrams on :9000' print('Receiving datagrams on :9000')
EchoServer(':9000').serve_forever() EchoServer(':9000').serve_forever()
from __future__ import print_function
import socket import socket
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.connect("./unixsocket_server.py.sock") s.connect("./unixsocket_server.py.sock")
s.send('GET / HTTP/1.0\r\n\r\n') s.send('GET / HTTP/1.0\r\n\r\n')
data = s.recv(1024) data = s.recv(1024)
print 'received %s bytes' % len(data) print('received %s bytes' % len(data))
print data print(data)
s.close() s.close()
#!/usr/bin/python #!/usr/bin/python
from __future__ import print_function
from gevent.wsgi import WSGIServer from gevent.wsgi import WSGIServer
from application import application from application import application
print 'Serving on 8000...' print('Serving on 8000...')
WSGIServer(('', 8000), application).serve_forever() WSGIServer(('', 8000), application).serve_forever()
...@@ -10,6 +10,7 @@ To start the server on some other interface/port, use ...@@ -10,6 +10,7 @@ To start the server on some other interface/port, use
python -m gevent.wsgi -p 8000 -i 0.0.0.0 webproxy.py python -m gevent.wsgi -p 8000 -i 0.0.0.0 webproxy.py
""" """
from __future__ import print_function
from gevent import monkey; monkey.patch_all() from gevent import monkey; monkey.patch_all()
import sys import sys
import re import re
...@@ -53,7 +54,7 @@ def proxy(path, start_response, proxy_url): ...@@ -53,7 +54,7 @@ def proxy(path, start_response, proxy_url):
response = urllib2.urlopen(path) response = urllib2.urlopen(path)
except urllib2.HTTPError as ex: except urllib2.HTTPError as ex:
response = ex response = ex
print ('%s: %s %s' % (path, response.code, response.msg)) print('%s: %s %s' % (path, response.code, response.msg))
headers = [(k, v) for (k, v) in response.headers.items() if k not in drop_headers] headers = [(k, v) for (k, v) in response.headers.items() if k not in drop_headers]
scheme, netloc, path, params, query, fragment = urlparse(path) scheme, netloc, path, params, query, fragment = urlparse(path)
host = (scheme or 'http') + '://' + netloc host = (scheme or 'http') + '://' + netloc
...@@ -97,7 +98,7 @@ def fix_links(data, proxy_url, host_url): ...@@ -97,7 +98,7 @@ def fix_links(data, proxy_url, host_url):
result = m.group('before') + '"' + join(proxy_url, url) + '"' result = m.group('before') + '"' + join(proxy_url, url) + '"'
else: else:
result = m.group('before') + '"' + join(proxy_url, host_url, url) + '"' result = m.group('before') + '"' + join(proxy_url, host_url, url) + '"'
#print 'replaced %r -> %r' % (m.group(0), result) #print('replaced %r -> %r' % (m.group(0), result))
return result return result
data = _link_re_1.sub(fix_link_cb, data) data = _link_re_1.sub(fix_link_cb, data)
data = _link_re_2.sub(fix_link_cb, data) data = _link_re_2.sub(fix_link_cb, data)
...@@ -122,5 +123,5 @@ FORM = """<html><head> ...@@ -122,5 +123,5 @@ FORM = """<html><head>
if __name__ == '__main__': if __name__ == '__main__':
from gevent.pywsgi import WSGIServer from gevent.pywsgi import WSGIServer
print 'Serving on %s...' % LISTEN print('Serving on %s...' % LISTEN)
WSGIServer(LISTEN, application).serve_forever() WSGIServer(LISTEN, application).serve_forever()
#!/usr/bin/python #!/usr/bin/python
"""A web.py application powered by gevent""" """A web.py application powered by gevent"""
from __future__ import print_function
from gevent import monkey; monkey.patch_all() from gevent import monkey; monkey.patch_all()
from gevent.pywsgi import WSGIServer from gevent.pywsgi import WSGIServer
import time import time
...@@ -21,12 +22,12 @@ class long_polling: ...@@ -21,12 +22,12 @@ class long_polling:
# and thanks to "monkey.patch_all()" statement at the top, thread-local storage used by web.ctx # and thanks to "monkey.patch_all()" statement at the top, thread-local storage used by web.ctx
# becomes greenlet-local storage thus making requests isolated as they should be. # becomes greenlet-local storage thus making requests isolated as they should be.
def GET(self): def GET(self):
print 'GET /long' print('GET /long')
time.sleep(10) # possible to block the request indefinitely, without harming others time.sleep(10) # possible to block the request indefinitely, without harming others
return 'Hello, 10 seconds later' return 'Hello, 10 seconds later'
if __name__ == "__main__": if __name__ == "__main__":
application = web.application(urls, globals()).wsgifunc() application = web.application(urls, globals()).wsgifunc()
print 'Serving on 8088...' print('Serving on 8088...')
WSGIServer(('', 8088), application).serve_forever() WSGIServer(('', 8088), application).serve_forever()
#!/usr/bin/python #!/usr/bin/python
"""WSGI server example""" """WSGI server example"""
from __future__ import print_function
from gevent.pywsgi import WSGIServer from gevent.pywsgi import WSGIServer
...@@ -13,5 +14,5 @@ def application(env, start_response): ...@@ -13,5 +14,5 @@ def application(env, start_response):
if __name__ == '__main__': if __name__ == '__main__':
print 'Serving on 8088...' print('Serving on 8088...')
WSGIServer(('', 8088), application).serve_forever() WSGIServer(('', 8088), application).serve_forever()
#!/usr/bin/python #!/usr/bin/python
"""Secure WSGI server example based on gevent.pywsgi""" """Secure WSGI server example based on gevent.pywsgi"""
from __future__ import print_function
from gevent import pywsgi from gevent import pywsgi
...@@ -12,7 +13,7 @@ def hello_world(env, start_response): ...@@ -12,7 +13,7 @@ def hello_world(env, start_response):
start_response('404 Not Found', [('Content-Type', 'text/html')]) start_response('404 Not Found', [('Content-Type', 'text/html')])
return ['<h1>Not Found</h1>'] return ['<h1>Not Found</h1>']
print 'Serving on https://127.0.0.1:8443' print('Serving on https://127.0.0.1:8443')
server = pywsgi.WSGIServer(('0.0.0.0', 8443), hello_world, keyfile='server.key', certfile='server.crt') server = pywsgi.WSGIServer(('0.0.0.0', 8443), hello_world, keyfile='server.key', certfile='server.crt')
# to start the server asynchronously, call server.start() # to start the server asynchronously, call server.start()
# we use blocking serve_forever() here because we have no other jobs # we use blocking serve_forever() here because we have no other jobs
......
...@@ -24,6 +24,7 @@ ...@@ -24,6 +24,7 @@
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE. # THE SOFTWARE.
from __future__ import print_function
import sys import sys
from code import InteractiveConsole from code import InteractiveConsole
...@@ -109,6 +110,6 @@ class _fileobject(socket._fileobject): ...@@ -109,6 +110,6 @@ class _fileobject(socket._fileobject):
if __name__ == '__main__': if __name__ == '__main__':
if not sys.argv[1:]: if not sys.argv[1:]:
print ('USAGE: %s PORT' % sys.argv[0]) print('USAGE: %s PORT' % sys.argv[0])
else: else:
BackdoorServer(('127.0.0.1', int(sys.argv[1]))).serve_forever() BackdoorServer(('127.0.0.1', int(sys.argv[1]))).serve_forever()
# Copyright (c) 2009-2012 Denis Bilenko. See LICENSE for details. # Copyright (c) 2009-2012 Denis Bilenko. See LICENSE for details.
"""Make the standard library cooperative.""" """Make the standard library cooperative."""
from __future__ import absolute_import from __future__ import absolute_import
from __future__ import print_function
import sys import sys
__all__ = ['patch_all', __all__ = ['patch_all',
...@@ -227,11 +228,11 @@ MONKEY OPTIONS: --verbose %s""" % ', '.join('--[no-]%s' % m for m in modules) ...@@ -227,11 +228,11 @@ MONKEY OPTIONS: --verbose %s""" % ', '.join('--[no-]%s' % m for m in modules)
if verbose: if verbose:
import pprint import pprint
import os import os
print ('gevent.monkey.patch_all(%s)' % ', '.join('%s=%s' % item for item in args.items())) 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.version=%s' % (sys.version.strip().replace('\n', ' '), ))
print ('sys.path=%s' % pprint.pformat(sys.path)) print('sys.path=%s' % pprint.pformat(sys.path))
print ('sys.modules=%s' % pprint.pformat(sorted(sys.modules.keys()))) print('sys.modules=%s' % pprint.pformat(sorted(sys.modules.keys())))
print ('cwd=%s' % os.getcwd()) print('cwd=%s' % os.getcwd())
patch_all(**args) patch_all(**args)
if argv: if argv:
...@@ -240,4 +241,4 @@ MONKEY OPTIONS: --verbose %s""" % ', '.join('--[no-]%s' % m for m in modules) ...@@ -240,4 +241,4 @@ MONKEY OPTIONS: --verbose %s""" % ', '.join('--[no-]%s' % m for m in modules)
globals()['__file__'] = sys.argv[0] # issue #302 globals()['__file__'] = sys.argv[0] # issue #302
execfile(sys.argv[0]) execfile(sys.argv[0])
else: else:
print (script_help) print(script_help)
...@@ -15,7 +15,7 @@ means repeatedly calling :meth:`get <Queue.get>` until :meth:`get <Queue.get>` r ...@@ -15,7 +15,7 @@ means repeatedly calling :meth:`get <Queue.get>` until :meth:`get <Queue.get>` r
>>> queue.put(2) >>> queue.put(2)
>>> queue.put(StopIteration) >>> queue.put(StopIteration)
>>> for item in queue: >>> for item in queue:
... print item ... print(item)
1 1
2 2
""" """
......
#! /usr/bin/env python #! /usr/bin/env python
from __future__ import print_function
import time import time
from gevent import socket from gevent import socket
from gevent.server import StreamServer from gevent.server import StreamServer
...@@ -24,10 +25,10 @@ def main(): ...@@ -24,10 +25,10 @@ def main():
start = time.time() start = time.time()
conn.sendall(data) conn.sendall(data)
spent = time.time() - start spent = time.time() - start
print ("%.2f MB/s" % (length / spent / 0x100000)) print("%.2f MB/s" % (length / spent / 0x100000))
spent_total += spent spent_total += spent
print ("~ %.2f MB/s" % (length * N / spent_total / 0x100000)) print("~ %.2f MB/s" % (length * N / spent_total / 0x100000))
server.stop() server.stop()
......
"""Benchmarking sleep(0) performance.""" """Benchmarking sleep(0) performance."""
from __future__ import print_function
import sys import sys
from time import time from time import time
try: try:
...@@ -29,7 +30,7 @@ def bench_gevent(arg=0): ...@@ -29,7 +30,7 @@ def bench_gevent(arg=0):
import gevent import gevent
from gevent import sleep from gevent import sleep
delta = test(sleep, arg) delta = test(sleep, arg)
print ('gevent %s (%s): sleep(%r): %.1f microseconds' % (gevent.__version__, gevent.__file__, arg, delta * 1000000. / N)) print('gevent %s (%s): sleep(%r): %.1f microseconds' % (gevent.__version__, gevent.__file__, arg, delta * 1000000. / N))
def bench_eventlet(arg): def bench_eventlet(arg):
...@@ -40,7 +41,7 @@ def bench_eventlet(arg): ...@@ -40,7 +41,7 @@ def bench_eventlet(arg):
return return
from eventlet.api import sleep from eventlet.api import sleep
delta = test(sleep, arg) delta = test(sleep, arg)
print ('eventlet %s (%s): sleep(%r): %.1f microseconds' % (eventlet.__version__, eventlet.__file__, arg, delta * 1000000. / N)) print('eventlet %s (%s): sleep(%r): %.1f microseconds' % (eventlet.__version__, eventlet.__file__, arg, delta * 1000000. / N))
def main(): def main():
......
"""Benchmarking spawn() performance. """Benchmarking spawn() performance.
""" """
from __future__ import print_function
import sys import sys
import os import os
import random import random
...@@ -29,13 +30,13 @@ def test(spawn, sleep, kwargs): ...@@ -29,13 +30,13 @@ def test(spawn, sleep, kwargs):
for _ in xrange(N): for _ in xrange(N):
spawn(incr, sleep, **kwargs) spawn(incr, sleep, **kwargs)
delta = time() - start 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 assert counter == 0, counter
start = time() start = time()
sleep(0) sleep(0)
delta = time() - start delta = time() - start
assert counter == N, (counter, N) 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): def bench_none(options):
...@@ -45,26 +46,26 @@ def bench_none(options): ...@@ -45,26 +46,26 @@ def bench_none(options):
incr(noop, **kwargs) incr(noop, **kwargs)
delta = time() - start delta = time() - start
assert counter == N, (counter, N) assert counter == N, (counter, N)
print ('%.2f microseconds' % (delta * 1000000.0 / N)) print('%.2f microseconds' % (delta * 1000000.0 / N))
def bench_gevent(options): def bench_gevent(options):
import gevent import gevent
print ('using gevent from %s' % gevent.__file__) print('using gevent from %s' % gevent.__file__)
from gevent import spawn, sleep from gevent import spawn, sleep
test(spawn, sleep, options.kwargs) test(spawn, sleep, options.kwargs)
def bench_geventraw(options): def bench_geventraw(options):
import gevent import gevent
print ('using gevent from %s' % gevent.__file__) print('using gevent from %s' % gevent.__file__)
from gevent import sleep, spawn_raw from gevent import sleep, spawn_raw
test(spawn_raw, sleep, options.kwargs) test(spawn_raw, sleep, options.kwargs)
def bench_geventpool(options): def bench_geventpool(options):
import gevent import gevent
print ('using gevent from %s' % gevent.__file__) print('using gevent from %s' % gevent.__file__)
from gevent import sleep from gevent import sleep
from gevent.pool import Pool from gevent.pool import Pool
p = Pool() p = Pool()
...@@ -72,7 +73,7 @@ def bench_geventpool(options): ...@@ -72,7 +73,7 @@ def bench_geventpool(options):
start = time() start = time()
p.join() p.join()
delta = time() - start 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): def bench_eventlet(options):
...@@ -82,7 +83,7 @@ def bench_eventlet(options): ...@@ -82,7 +83,7 @@ def bench_eventlet(options):
if options.ignore_import_errors: if options.ignore_import_errors:
return return
raise raise
print ('using eventlet from %s' % eventlet.__file__) print('using eventlet from %s' % eventlet.__file__)
from eventlet.api import spawn, sleep, use_hub from eventlet.api import spawn, sleep, use_hub
if options.eventlet_hub is not None: if options.eventlet_hub is not None:
use_hub(options.eventlet_hub) use_hub(options.eventlet_hub)
...@@ -96,13 +97,13 @@ def bench_eventlet1(options): ...@@ -96,13 +97,13 @@ def bench_eventlet1(options):
if options.ignore_import_errors: if options.ignore_import_errors:
return return
raise 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.proc import spawn_greenlet as spawn
from eventlet.api import sleep, use_hub from eventlet.api import sleep, use_hub
if options.eventlet_hub: if options.eventlet_hub:
use_hub(options.eventlet_hub) use_hub(options.eventlet_hub)
if options.with_kwargs: if options.with_kwargs:
print ('eventlet.proc.spawn_greenlet does support kwargs') print('eventlet.proc.spawn_greenlet does support kwargs')
return return
test(spawn, sleep, options.kwargs) test(spawn, sleep, options.kwargs)
...@@ -114,21 +115,21 @@ def bench_all(options): ...@@ -114,21 +115,21 @@ def bench_all(options):
random.shuffle(names) random.shuffle(names)
for func in names: for func in names:
cmd = '%s %s %s --ignore-import-errors' % (sys.executable, __file__, func) cmd = '%s %s %s --ignore-import-errors' % (sys.executable, __file__, func)
print (cmd) print(cmd)
sys.stdout.flush() sys.stdout.flush()
time.sleep(0.01) time.sleep(0.01)
if os.system(cmd): if os.system(cmd):
error = 1 error = 1
print ('%s failed' % cmd) print('%s failed' % cmd)
print ('') print('')
for func in names: for func in names:
cmd = '%s %s --with-kwargs %s --ignore-import-errors' % (sys.executable, __file__, func) cmd = '%s %s --with-kwargs %s --ignore-import-errors' % (sys.executable, __file__, func)
print (cmd) print(cmd)
sys.stdout.flush() sys.stdout.flush()
if os.system(cmd): if os.system(cmd):
error = 1 error = 1
print ('%s failed' % cmd) print('%s failed' % cmd)
print ('') print('')
if error: if error:
sys.exit(1) sys.exit(1)
......
...@@ -12,7 +12,7 @@ else: ...@@ -12,7 +12,7 @@ else:
test_filename = sys.argv[1] test_filename = sys.argv[1]
del sys.argv[1] del sys.argv[1]
print 'Running with patch_all(%s): %s' % (','.join('%s=%r' % x for x in kwargs.items()), test_filename) print('Running with patch_all(%s): %s' % (','.join('%s=%r' % x for x in kwargs.items()), test_filename))
from gevent import monkey; monkey.patch_all(**kwargs) from gevent import monkey; monkey.patch_all(**kwargs)
......
from __future__ import print_function
import sys import sys
import os import os
import re import re
...@@ -181,5 +182,5 @@ def disable_tests_in_source(source, name): ...@@ -181,5 +182,5 @@ def disable_tests_in_source(source, name):
# XXX ignoring TestCase class name # XXX ignoring TestCase class name
testcase = test.split('.')[-1] testcase = test.split('.')[-1]
source, n = re.subn(testcase, 'XXX' + testcase, source) 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 return source
...@@ -17,7 +17,6 @@ if PY3: ...@@ -17,7 +17,6 @@ if PY3:
raise value.with_traceback(tb) raise value.with_traceback(tb)
raise value raise value
print_ = getattr(builtins, "print")
del builtins del builtins
xrange = range xrange = range
......
"""Check __all__, __implements__, __extensions__, __imports__ of the modules""" """Check __all__, __implements__, __extensions__, __imports__ of the modules"""
from __future__ import print_function
import sys import sys
import unittest import unittest
import types import types
...@@ -119,7 +120,7 @@ class Test(unittest.TestCase): ...@@ -119,7 +120,7 @@ class Test(unittest.TestCase):
result = [] result = []
for name in missed[:]: for name in missed[:]:
if name in not_implemented: if name in not_implemented:
print ('IncompleteImplWarning: %s.%s' % (self.modname, name)) print('IncompleteImplWarning: %s.%s' % (self.modname, name))
else: else:
result.append(name) result.append(name)
missed = result missed = result
......
from __future__ import print_function
from __future__ import with_statement from __future__ import with_statement
import gevent import gevent
import gevent.core import gevent.core
...@@ -18,4 +19,4 @@ start = time.time() ...@@ -18,4 +19,4 @@ start = time.time()
with gevent.Timeout(0.3): with gevent.Timeout(0.3):
hub.wait(watcher) hub.wait(watcher)
print 'Watcher %r reacted after %.6f seconds' % (watcher, time.time() - start - 0.1) print('Watcher %r reacted after %.6f seconds' % (watcher, time.time() - start - 0.1))
from __future__ import print_function
import sys import sys
from gevent import core, signal from gevent import core, signal
loop = core.loop() loop = core.loop()
...@@ -5,13 +6,13 @@ loop = core.loop() ...@@ -5,13 +6,13 @@ loop = core.loop()
signal = signal(2, sys.stderr.write, 'INTERRUPT!') signal = signal(2, sys.stderr.write, 'INTERRUPT!')
print ('must exit immediatelly...') print('must exit immediatelly...')
loop.run() # must exit immediatelly loop.run() # must exit immediatelly
print ('...and once more...') print('...and once more...')
loop.run() # repeating does not fail loop.run() # repeating does not fail
print ('..done') print('..done')
print ('must exit after 0.5 seconds.') print('must exit after 0.5 seconds.')
timer = loop.timer(0.5) timer = loop.timer(0.5)
timer.start(lambda: None) timer.start(lambda: None)
loop.run() loop.run()
......
from __future__ import print_function
from __future__ import with_statement from __future__ import with_statement
import gevent import gevent
import gevent.core import gevent.core
...@@ -31,9 +32,9 @@ try: ...@@ -31,9 +32,9 @@ try:
hub.wait(watcher) hub.wait(watcher)
reaction = time.time() - start - DELAY reaction = time.time() - start - DELAY
print 'Watcher %s reacted after %.4f seconds (write)' % (watcher, reaction) print('Watcher %s reacted after %.4f seconds (write)' % (watcher, reaction))
if reaction >= DELAY and EV_USE_INOTIFY: if reaction >= DELAY and EV_USE_INOTIFY:
print 'WARNING: inotify failed (write)' print('WARNING: inotify failed (write)')
assert reaction >= 0.0, 'Watcher %s reacted too early (write): %.3fs' % (watcher, reaction) assert reaction >= 0.0, 'Watcher %s reacted too early (write): %.3fs' % (watcher, reaction)
assert watcher.attr is not None, watcher.attr assert watcher.attr is not None, watcher.attr
assert watcher.prev is not None, watcher.prev assert watcher.prev is not None, watcher.prev
...@@ -47,9 +48,9 @@ try: ...@@ -47,9 +48,9 @@ try:
hub.wait(watcher) hub.wait(watcher)
reaction = time.time() - start - DELAY reaction = time.time() - start - DELAY
print 'Watcher %s reacted after %.4f seconds (unlink)' % (watcher, reaction) print('Watcher %s reacted after %.4f seconds (unlink)' % (watcher, reaction))
if reaction >= DELAY and EV_USE_INOTIFY: if reaction >= DELAY and EV_USE_INOTIFY:
print 'WARNING: inotify failed (unlink)' print('WARNING: inotify failed (unlink)')
assert reaction >= 0.0, 'Watcher %s reacted too early (unlink): %.3fs' % (watcher, reaction) assert reaction >= 0.0, 'Watcher %s reacted too early (unlink): %.3fs' % (watcher, reaction)
assert watcher.attr is None, watcher.attr assert watcher.attr is None, watcher.attr
assert watcher.prev is not None, watcher.prev assert watcher.prev is not None, watcher.prev
......
from __future__ import print_function
from gevent import core from gevent import core
called = [] called = []
...@@ -34,8 +35,8 @@ if __name__ == '__main__': ...@@ -34,8 +35,8 @@ if __name__ == '__main__':
gettotalrefcount = getattr(sys, 'gettotalrefcount', None) gettotalrefcount = getattr(sys, 'gettotalrefcount', None)
called[:] = [] called[:] = []
if gettotalrefcount is not None: if gettotalrefcount is not None:
print (gettotalrefcount()) print(gettotalrefcount())
main() main()
called[:] = [] called[:] = []
if gettotalrefcount is not None: if gettotalrefcount is not None:
print (gettotalrefcount()) print(gettotalrefcount())
from __future__ import print_function
import gevent import gevent
# Loop of initial Hub is default loop. # Loop of initial Hub is default loop.
hub = gevent.get_hub() hub = gevent.get_hub()
...@@ -12,7 +13,7 @@ saved_loop = hub.loop ...@@ -12,7 +13,7 @@ saved_loop = hub.loop
# Destroy hub including default loop. # Destroy hub including default loop.
hub.destroy(destroy_loop=True) hub.destroy(destroy_loop=True)
assert saved_loop.fileno() is None, saved_loop assert saved_loop.fileno() is None, saved_loop
print hub, saved_loop print(hub, saved_loop)
# Create new hub and explicitly request creation of a new default loop. # Create new hub and explicitly request creation of a new default loop.
hub = gevent.get_hub(default=True) hub = gevent.get_hub(default=True)
......
from __future__ import print_function
import sys import sys
import os import os
import re import re
...@@ -21,7 +22,7 @@ if __name__ == '__main__': ...@@ -21,7 +22,7 @@ if __name__ == '__main__':
allowed_modules = sys.argv[1:] allowed_modules = sys.argv[1:]
sys.path.append('.') sys.path.append('.')
base = os.path.dirname(gevent.__file__) base = os.path.dirname(gevent.__file__)
print (base) print(base)
os.chdir('..') os.chdir('..')
globs = {'myfunction': myfunction, 'gevent': gevent, 'socket': socket} globs = {'myfunction': myfunction, 'gevent': gevent, 'socket': socket}
...@@ -47,14 +48,14 @@ if __name__ == '__main__': ...@@ -47,14 +48,14 @@ if __name__ == '__main__':
if re.search('^\s*>>> ', open(path).read(), re.M): if re.search('^\s*>>> ', open(path).read(), re.M):
try: try:
s = doctest.DocTestSuite(m, extraglobs=globs) 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) suite.addTest(s)
modules_count += 1 modules_count += 1
tests_count += len(s._tests) tests_count += len(s._tests)
except Exception: except Exception:
traceback.print_exc() traceback.print_exc()
sys.stderr.write('Failed to process %s\n\n' % path) 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 = unittest.TextTestRunner(verbosity=2)
runner.run(suite) runner.run(suite)
finally: finally:
......
from __future__ import print_function
from __future__ import with_statement from __future__ import with_statement
from gevent import monkey; monkey.patch_all() from gevent import monkey; monkey.patch_all()
import sys import sys
...@@ -26,7 +27,7 @@ class Test(util.TestServer): ...@@ -26,7 +27,7 @@ class Test(util.TestServer):
def handle(socket, address): def handle(socket, address):
while True: while True:
data = socket.recv(1024) data = socket.recv(1024)
print 'got %r' % data print('got %r' % data)
if not data: if not data:
break break
log.append(data) log.append(data)
......
from __future__ import print_function
import sys import sys
...@@ -17,7 +18,7 @@ elif sys.argv[1:] == ['subprocess']: ...@@ -17,7 +18,7 @@ elif sys.argv[1:] == ['subprocess']:
def printline(): def printline():
line = raw_input() line = raw_input()
print '%s chars.' % len(line) print('%s chars.' % len(line))
gevent.spawn(printline).join() gevent.spawn(printline).join()
......
...@@ -17,6 +17,7 @@ ...@@ -17,6 +17,7 @@
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE. # THE SOFTWARE.
from __future__ import print_function
from gevent import monkey from gevent import monkey
monkey.patch_all(thread=False) monkey.patch_all(thread=False)
...@@ -71,7 +72,7 @@ def read_headers(fd): ...@@ -71,7 +72,7 @@ def read_headers(fd):
try: try:
key, value = line.split(': ', 1) key, value = line.split(': ', 1)
except: except:
print 'Failed to split: %r' % (line, ) print('Failed to split: %r' % (line, ))
raise 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 headers.keys()], 'Header %r:%r sent more than once: %r' % (key, value, headers)
headers[key] = value headers[key] = value
...@@ -85,7 +86,7 @@ def iread_chunks(fd): ...@@ -85,7 +86,7 @@ def iread_chunks(fd):
try: try:
chunk_size = int(chunk_size, 16) chunk_size = int(chunk_size, 16)
except: except:
print 'Failed to parse chunk size: %r' % line print('Failed to parse chunk size: %r' % line)
raise raise
if chunk_size == 0: if chunk_size == 0:
crlf = fd.read(2) crlf = fd.read(2)
...@@ -107,7 +108,7 @@ class Response(object): ...@@ -107,7 +108,7 @@ class Response(object):
try: try:
version, code, self.reason = status_line[:-2].split(' ', 2) version, code, self.reason = status_line[:-2].split(' ', 2)
except Exception: except Exception:
print 'Error: %r' % status_line print('Error: %r' % status_line)
raise raise
self.code = int(code) self.code = int(code)
HTTP, self.version = version.split('/') HTTP, self.version = version.split('/')
...@@ -164,7 +165,7 @@ class Response(object): ...@@ -164,7 +165,7 @@ class Response(object):
try: try:
if 'chunked' in headers.get('Transfer-Encoding', ''): if 'chunked' in headers.get('Transfer-Encoding', ''):
if CONTENT_LENGTH in headers: 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.chunks = list(iread_chunks(fd))
self.body = ''.join(self.chunks) self.body = ''.join(self.chunks)
elif CONTENT_LENGTH in headers: elif CONTENT_LENGTH in headers:
...@@ -173,7 +174,7 @@ class Response(object): ...@@ -173,7 +174,7 @@ class Response(object):
else: else:
self.body = fd.read() self.body = fd.read()
except: except:
print 'Response.read failed to read the body:\n%s' % self print('Response.read failed to read the body:\n%s' % self)
raise raise
if body is not None: if body is not None:
self.assertBody(body) self.assertBody(body)
...@@ -192,13 +193,13 @@ class DebugFileObject(object): ...@@ -192,13 +193,13 @@ class DebugFileObject(object):
def read(self, *args): def read(self, *args):
result = self.obj.read(*args) result = self.obj.read(*args)
if DEBUG: if DEBUG:
print repr(result) print(repr(result))
return result return result
def readline(self, *args): def readline(self, *args):
result = self.obj.readline(*args) result = self.obj.readline(*args)
if DEBUG: if DEBUG:
print repr(result) print(repr(result))
return result return result
def __getattr__(self, item): def __getattr__(self, item):
...@@ -924,7 +925,7 @@ class ChunkedInputTests(TestCase): ...@@ -924,7 +925,7 @@ class ChunkedInputTests(TestCase):
def test_short_read_with_zero_content_length(self): def test_short_read_with_zero_content_length(self):
body = self.body() body = self.body()
req = "POST /short-read HTTP/1.1\r\ntransfer-encoding: Chunked\r\nContent-Length:0\r\n\r\n" + 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 = self.connect().makefile(bufsize=1)
fd.write(req) fd.write(req)
...@@ -953,7 +954,7 @@ class ChunkedInputTests(TestCase): ...@@ -953,7 +954,7 @@ class ChunkedInputTests(TestCase):
except AssertionError as ex: except AssertionError as ex:
if str(ex).startswith('Unexpected code: 400'): if str(ex).startswith('Unexpected code: 400'):
if not server_implements_chunked: if not server_implements_chunked:
print 'ChunkedNotImplementedWarning' print('ChunkedNotImplementedWarning')
return return
raise raise
...@@ -1005,7 +1006,7 @@ class Expect100ContinueTests(TestCase): ...@@ -1005,7 +1006,7 @@ class Expect100ContinueTests(TestCase):
except AssertionError as ex: except AssertionError as ex:
if str(ex).startswith('Unexpected code: 400'): if str(ex).startswith('Unexpected code: 400'):
if not server_implements_100continue: if not server_implements_100continue:
print '100ContinueNotImplementedWarning' print('100ContinueNotImplementedWarning')
return return
raise raise
......
...@@ -22,6 +22,7 @@ ...@@ -22,6 +22,7 @@
"""This test checks that underlying socket instances (gevent.socket.socket._sock) """This test checks that underlying socket instances (gevent.socket.socket._sock)
are not leaked by the hub. are not leaked by the hub.
""" """
from __future__ import print_function
from _socket import socket from _socket import socket
...@@ -63,26 +64,26 @@ def handle_request(s, raise_on_timeout): ...@@ -63,26 +64,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(('127.0.0.1', port)) s.connect(('127.0.0.1', 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()
...@@ -93,7 +94,7 @@ def run_interaction(run_client): ...@@ -93,7 +94,7 @@ def run_interaction(run_client):
port = s.getsockname()[1] port = s.getsockname()[1]
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._sock) #print(sys.getrefcount(s._sock))
#s.close() #s.close()
return weakref.ref(s._sock) return weakref.ref(s._sock)
...@@ -101,11 +102,11 @@ def run_interaction(run_client): ...@@ -101,11 +102,11 @@ def run_interaction(run_client):
def run_and_check(run_client): def run_and_check(run_client):
w = run_interaction(run_client=run_client) w = run_interaction(run_client=run_client)
if w(): if w():
print pformat(gc.get_referrers(w())) print(pformat(gc.get_referrers(w())))
for x in gc.get_referrers(w()): for x in gc.get_referrers(w()):
print pformat(x) print(pformat(x))
for y in gc.get_referrers(x): for y in gc.get_referrers(x):
print '-', pformat(y) print('-', pformat(y))
raise AssertionError('server should be dead by now') raise AssertionError('server should be dead by now')
......
from __future__ import print_function
import greentest import greentest
from gevent import socket from gevent import socket
import gevent import gevent
...@@ -16,7 +17,7 @@ class SimpleStreamServer(StreamServer): ...@@ -16,7 +17,7 @@ class SimpleStreamServer(StreamServer):
try: try:
method, path, rest = request_line.split(' ', 3) method, path, rest = request_line.split(' ', 3)
except Exception: except Exception:
print ('Failed to parse request line: %r' % (request_line, )) print('Failed to parse request line: %r' % (request_line, ))
raise raise
if path == '/ping': if path == '/ping':
client_socket.sendall('HTTP/1.0 200 OK\r\n\r\nPONG') client_socket.sendall('HTTP/1.0 200 OK\r\n\r\nPONG')
...@@ -141,9 +142,9 @@ class TestCase(greentest.TestCase): ...@@ -141,9 +142,9 @@ class TestCase(greentest.TestCase):
def report_netstat(self, msg): def report_netstat(self, msg):
return return
print (msg) print(msg)
os.system('sudo netstat -anp | grep %s' % os.getpid()) os.system('sudo netstat -anp | grep %s' % os.getpid())
print ('^^^^^') print('^^^^^')
def init_server(self): def init_server(self):
self.server = self.ServerSubClass(('127.0.0.1', 0)) self.server = self.ServerSubClass(('127.0.0.1', 0))
......
from __future__ import print_function
from __future__ import with_statement from __future__ import with_statement
import sys import sys
...@@ -57,7 +58,7 @@ class ThreadTrace(unittest.TestCase): ...@@ -57,7 +58,7 @@ class ThreadTrace(unittest.TestCase):
try: try:
def trace(frame, ev, arg): def trace(frame, ev, arg):
lst.append((frame.f_code.co_filename, frame.f_lineno, ev)) 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 return trace
with gevent.thread.allocate_lock(): with gevent.thread.allocate_lock():
......
from __future__ import print_function
import sys import sys
import gevent import gevent
from gevent.resolver_ares import Resolver from gevent.resolver_ares import Resolver
from gevent import socket from gevent import socket
print gevent.__file__ print(gevent.__file__)
address = ('127.0.0.10', 53) address = ('127.0.0.10', 53)
listener = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) listener = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
...@@ -17,7 +18,7 @@ except socket.error as ex: ...@@ -17,7 +18,7 @@ except socket.error as ex:
def reader(): def reader():
while True: while True:
print listener.recvfrom(10000) print(listener.recvfrom(10000))
gevent.spawn(reader) gevent.spawn(reader)
......
from __future__ import print_function
import os import os
import gevent import gevent
from gevent import core from gevent import core
...@@ -11,18 +12,18 @@ for count in xrange(2): ...@@ -11,18 +12,18 @@ for count in xrange(2):
gevent.sleep(0.001) gevent.sleep(0.001)
fileno = hub.loop.fileno() fileno = hub.loop.fileno()
if fileno is not None: if fileno is not None:
print '%s. Testing %r: %r' % (count, backend, hub) print('%s. Testing %r: %r' % (count, backend, hub))
os.close(fileno) os.close(fileno)
try: try:
gevent.sleep(0.001) gevent.sleep(0.001)
except SystemError as ex: except SystemError as ex:
if '(libev)' in str(ex): if '(libev)' in str(ex):
print 'The error is expected: %s' % ex print('The error is expected: %s' % ex)
else: else:
raise raise
else: else:
raise AssertionError('gevent.sleep() is expected to fail after loop fd was closed') raise AssertionError('gevent.sleep() is expected to fail after loop fd was closed')
else: else:
print '%s. %r lacks fileno()' % (count, backend) print('%s. %r lacks fileno()' % (count, backend))
hub.destroy() hub.destroy()
assert 'destroyed' in repr(hub), repr(hub) assert 'destroyed' in repr(hub), repr(hub)
"""Supporting definitions for the Python regression tests.""" """Supporting definitions for the Python regression tests."""
from __future__ import print_function
import sys import sys
HOST = 'localhost' HOST = 'localhost'
...@@ -175,8 +176,9 @@ def bind_port(sock, host='', preferred_port=54321): ...@@ -175,8 +176,9 @@ def bind_port(sock, host='', preferred_port=54321):
except socket.error: except socket.error:
if sys.exc_info()[1].args[0] != errno.EADDRINUSE: if sys.exc_info()[1].args[0] != errno.EADDRINUSE:
raise raise
print >>sys.__stderr__, \ print(
' WARNING: failed to listen on port %d, trying another' % port ' WARNING: failed to listen on port %d, trying another' %
port, file=sys.__stderr__)
raise TestFailed('unable to find port to listen on') raise TestFailed('unable to find port to listen on')
FUZZ = 1e-6 FUZZ = 1e-6
...@@ -262,8 +264,8 @@ except IOError: ...@@ -262,8 +264,8 @@ except IOError:
fp = open(TMP_TESTFN, 'w+') fp = open(TMP_TESTFN, 'w+')
TESTFN = TMP_TESTFN TESTFN = TMP_TESTFN
except IOError: except IOError:
print ('WARNING: tests will fail, unable to write to: %s or %s' % print('WARNING: tests will fail, unable to write to: %s or %s' %
(TESTFN, TMP_TESTFN)) (TESTFN, TMP_TESTFN))
if fp is not None: if fp is not None:
fp.close() fp.close()
unlink(TESTFN) unlink(TESTFN)
...@@ -321,7 +323,7 @@ def check_syntax(statement): ...@@ -321,7 +323,7 @@ def check_syntax(statement):
except SyntaxError: except SyntaxError:
pass pass
else: else:
print ('Missing SyntaxError: "%s"' % statement) print('Missing SyntaxError: "%s"' % statement)
def open_urlresource(url): def open_urlresource(url):
import urllib, urlparse import urllib, urlparse
...@@ -335,7 +337,7 @@ def open_urlresource(url): ...@@ -335,7 +337,7 @@ def open_urlresource(url):
return open(fn) return open(fn)
requires('urlfetch') requires('urlfetch')
print >> get_original_stdout(), '\tfetching %s ...' % url print('\tfetching %s ...' % url, file=get_original_stdout())
fn, _ = urllib.urlretrieve(url, filename) fn, _ = urllib.urlretrieve(url, filename)
return open(fn) return open(fn)
...@@ -543,7 +545,7 @@ def run_doctest(module, verbosity=None): ...@@ -543,7 +545,7 @@ def run_doctest(module, verbosity=None):
finally: finally:
sys.stdout = save_stdout sys.stdout = save_stdout
if verbose: if verbose:
print ('doctest (%s) ... %d tests with zero failures' % (module.__name__, t)) print('doctest (%s) ... %d tests with zero failures' % (module.__name__, t))
return f, t return f, t
#======================================================================= #=======================================================================
...@@ -560,13 +562,13 @@ def threading_cleanup(num_active, num_limbo): ...@@ -560,13 +562,13 @@ def threading_cleanup(num_active, num_limbo):
_MAX_COUNT = 10 _MAX_COUNT = 10
count = 0 count = 0
while len(threading._active) != num_active and count < _MAX_COUNT: while len(threading._active) != num_active and count < _MAX_COUNT:
print (threading._active) print(threading._active)
count += 1 count += 1
time.sleep(0.1) time.sleep(0.1)
count = 0 count = 0
while len(threading._limbo) != num_limbo and count < _MAX_COUNT: while len(threading._limbo) != num_limbo and count < _MAX_COUNT:
print (threading._limbo) print(threading._limbo)
count += 1 count += 1
time.sleep(0.1) time.sleep(0.1)
......
# testing gevent's Event, Lock, RLock, Semaphore, BoundedSemaphore with standard test_threading # testing gevent's Event, Lock, RLock, Semaphore, BoundedSemaphore with standard test_threading
from __future__ import print_function
from __future__ import with_statement from __future__ import with_statement
from six import xrange from six import xrange
...@@ -75,26 +76,26 @@ class TestThread(threading.Thread): ...@@ -75,26 +76,26 @@ class TestThread(threading.Thread):
def run(self): def run(self):
delay = random.random() / 10000.0 delay = random.random() / 10000.0
if verbose: if verbose:
print 'task %s will run for %.1f usec' % ( print('task %s will run for %.1f usec' % (
self.name, delay * 1e6) self.name, delay * 1e6))
with self.sema: with self.sema:
with self.mutex: with self.mutex:
self.nrunning.inc() self.nrunning.inc()
if verbose: if verbose:
print self.nrunning.get(), 'tasks are running' print(self.nrunning.get(), 'tasks are running')
self.testcase.assert_(self.nrunning.get() <= 3) self.testcase.assert_(self.nrunning.get() <= 3)
time.sleep(delay) time.sleep(delay)
if verbose: if verbose:
print 'task', self.name, 'done' print('task', self.name, 'done')
with self.mutex: with self.mutex:
self.nrunning.dec() self.nrunning.dec()
self.testcase.assert_(self.nrunning.get() >= 0) self.testcase.assert_(self.nrunning.get() >= 0)
if verbose: if verbose:
print '%s is finished. %d tasks are running' % ( print('%s is finished. %d tasks are running' % (
self.name, self.nrunning.get()) self.name, self.nrunning.get()))
class ThreadTests(unittest.TestCase): class ThreadTests(unittest.TestCase):
...@@ -122,7 +123,7 @@ class ThreadTests(unittest.TestCase): ...@@ -122,7 +123,7 @@ class ThreadTests(unittest.TestCase):
t.start() t.start()
if verbose: if verbose:
print 'waiting for all tasks to complete' print('waiting for all tasks to complete')
for t in threads: for t in threads:
t.join(NUMTASKS) t.join(NUMTASKS)
self.assert_(not t.is_alive()) self.assert_(not t.is_alive())
...@@ -131,7 +132,7 @@ class ThreadTests(unittest.TestCase): ...@@ -131,7 +132,7 @@ class ThreadTests(unittest.TestCase):
self.assertFalse(t.ident is None) self.assertFalse(t.ident is None)
self.assert_(re.match('<TestThread\(.*, \w+ -?\d+\)>', repr(t))) self.assert_(re.match('<TestThread\(.*, \w+ -?\d+\)>', repr(t)))
if verbose: if verbose:
print 'all tasks done' print('all tasks done')
self.assertEqual(numrunning.get(), 0) self.assertEqual(numrunning.get(), 0)
if sys.version_info[:2] > (2, 5): if sys.version_info[:2] > (2, 5):
...@@ -153,12 +154,12 @@ class ThreadTests(unittest.TestCase): ...@@ -153,12 +154,12 @@ class ThreadTests(unittest.TestCase):
# run with a small(ish) thread stack size (256kB) # run with a small(ish) thread stack size (256kB)
def test_various_ops_small_stack(self): def test_various_ops_small_stack(self):
if verbose: if verbose:
print 'with 256kB thread stack size...' print('with 256kB thread stack size...')
try: try:
threading.stack_size(262144) threading.stack_size(262144)
except thread.error: except thread.error:
if verbose: if verbose:
print 'platform does not support changing thread stack size' print('platform does not support changing thread stack size')
return return
self.test_various_ops() self.test_various_ops()
threading.stack_size(0) threading.stack_size(0)
...@@ -166,12 +167,12 @@ class ThreadTests(unittest.TestCase): ...@@ -166,12 +167,12 @@ class ThreadTests(unittest.TestCase):
# run with a large thread stack size (1MB) # run with a large thread stack size (1MB)
def test_various_ops_large_stack(self): def test_various_ops_large_stack(self):
if verbose: if verbose:
print 'with 1MB thread stack size...' print('with 1MB thread stack size...')
try: try:
threading.stack_size(0x100000) threading.stack_size(0x100000)
except thread.error: except thread.error:
if verbose: if verbose:
print 'platform does not support changing thread stack size' print('platform does not support changing thread stack size')
return return
self.test_various_ops() self.test_various_ops()
threading.stack_size(0) threading.stack_size(0)
...@@ -202,7 +203,7 @@ class ThreadTests(unittest.TestCase): ...@@ -202,7 +203,7 @@ class ThreadTests(unittest.TestCase):
import ctypes import ctypes
except ImportError: except ImportError:
if verbose: if verbose:
print "test_PyThreadState_SetAsyncExc can't import ctypes" print("test_PyThreadState_SetAsyncExc can't import ctypes")
return # can't do anything return # can't do anything
set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc
...@@ -236,31 +237,31 @@ class ThreadTests(unittest.TestCase): ...@@ -236,31 +237,31 @@ class ThreadTests(unittest.TestCase):
t.daemon = True # so if this fails, we don't hang Python at shutdown t.daemon = True # so if this fails, we don't hang Python at shutdown
t.start() t.start()
if verbose: if verbose:
print " started worker thread" print(" started worker thread")
# Try a thread id that doesn't make sense. # Try a thread id that doesn't make sense.
if verbose: if verbose:
print " trying nonsensical thread id" print(" trying nonsensical thread id")
result = set_async_exc(ctypes.c_long(-1), exception) result = set_async_exc(ctypes.c_long(-1), exception)
self.assertEqual(result, 0) # no thread states modified self.assertEqual(result, 0) # no thread states modified
# Now raise an exception in the worker thread. # Now raise an exception in the worker thread.
if verbose: if verbose:
print " waiting for worker thread to get started" print(" waiting for worker thread to get started")
worker_started.wait() worker_started.wait()
if verbose: if verbose:
print " verifying worker hasn't exited" print(" verifying worker hasn't exited")
self.assert_(not t.finished) self.assert_(not t.finished)
if verbose: if verbose:
print " attempting to raise asynch exception in worker" print(" attempting to raise asynch exception in worker")
result = set_async_exc(ctypes.c_long(t.id), exception) result = set_async_exc(ctypes.c_long(t.id), exception)
self.assertEqual(result, 1) # one thread state modified self.assertEqual(result, 1) # one thread state modified
if verbose: if verbose:
print " waiting for worker to say it caught the exception" print(" waiting for worker to say it caught the exception")
worker_saw_exception.wait(timeout=10) worker_saw_exception.wait(timeout=10)
self.assert_(t.finished) self.assert_(t.finished)
if verbose: if verbose:
print " all OK -- joining worker" print(" all OK -- joining worker")
if t.finished: if t.finished:
t.join() t.join()
# else the thread is still running, and we have no way to kill it # else the thread is still running, and we have no way to kill it
...@@ -338,7 +339,7 @@ class ThreadTests(unittest.TestCase): ...@@ -338,7 +339,7 @@ class ThreadTests(unittest.TestCase):
sleep(1) sleep(1)
# As a non-daemon thread we SHOULD wake up and nothing # As a non-daemon thread we SHOULD wake up and nothing
# should be torn down yet # should be torn down yet
print "Woke up, sleep function is:", sleep print("Woke up, sleep function is: %%r" %% sleep)
threading.Thread(target=child).start() threading.Thread(target=child).start()
raise SystemExit raise SystemExit
...@@ -413,7 +414,7 @@ class ThreadJoinOnShutdown(unittest.TestCase): ...@@ -413,7 +414,7 @@ class ThreadJoinOnShutdown(unittest.TestCase):
# a thread, which waits for the main program to terminate # a thread, which waits for the main program to terminate
def joiningfunc(mainthread): def joiningfunc(mainthread):
mainthread.join() mainthread.join()
print 'end of thread' print('end of thread')
\n""" % setup_3 + script \n""" % setup_3 + script
import subprocess import subprocess
...@@ -432,7 +433,7 @@ class ThreadJoinOnShutdown(unittest.TestCase): ...@@ -432,7 +433,7 @@ class ThreadJoinOnShutdown(unittest.TestCase):
args=(threading.current_thread(),)) args=(threading.current_thread(),))
t.start() t.start()
time.sleep(0.1) time.sleep(0.1)
print 'end of main' print('end of main')
""" """
self._run_and_join(script) self._run_and_join(script)
...@@ -450,7 +451,7 @@ class ThreadJoinOnShutdown(unittest.TestCase): ...@@ -450,7 +451,7 @@ class ThreadJoinOnShutdown(unittest.TestCase):
t = threading.Thread(target=joiningfunc, t = threading.Thread(target=joiningfunc,
args=(threading.current_thread(),)) args=(threading.current_thread(),))
t.start() t.start()
print 'end of main' print('end of main')
""" """
self._run_and_join(script) self._run_and_join(script)
...@@ -464,8 +465,8 @@ class ThreadJoinOnShutdown(unittest.TestCase): ...@@ -464,8 +465,8 @@ class ThreadJoinOnShutdown(unittest.TestCase):
# See http://bugs.python.org/issue3863. # See http://bugs.python.org/issue3863.
# skip disable because I think the bug shouldn't apply to gevent -- denis # skip disable because I think the bug shouldn't apply to gevent -- denis
#if sys.platform in ('freebsd4', 'freebsd5', 'freebsd6', 'os2emx'): #if sys.platform in ('freebsd4', 'freebsd5', 'freebsd6', 'os2emx'):
# print >>sys.stderr, ('Skipping test_3_join_in_forked_from_thread' # print(('Skipping test_3_join_in_forked_from_thread'
# ' due to known OS bugs on'), sys.platform # ' due to known OS bugs on'), sys.platform, file=sys.stderr)
# return # return
script = """if 1: script = """if 1:
main_thread = threading.current_thread() main_thread = threading.current_thread()
...@@ -477,7 +478,7 @@ class ThreadJoinOnShutdown(unittest.TestCase): ...@@ -477,7 +478,7 @@ class ThreadJoinOnShutdown(unittest.TestCase):
t = threading.Thread(target=joiningfunc, t = threading.Thread(target=joiningfunc,
args=(main_thread,)) args=(main_thread,))
print 'end of main' print('end of main')
t.start() t.start()
t.join() # Should not block: main_thread is already stopped t.join() # Should not block: main_thread is already stopped
......
#!/usr/bin/env python #!/usr/bin/env python
from __future__ import print_function
import gevent import gevent
gevent.get_hub('select') # this is just to make sure we don't pass any fds to children gevent.get_hub('select') # this is just to make sure we don't pass any fds to children
from gevent import monkey; monkey.patch_all() from gevent import monkey; monkey.patch_all()
...@@ -137,8 +138,8 @@ def main(): ...@@ -137,8 +138,8 @@ def main():
tests = discover(args, options.ignore) tests = discover(args, options.ignore)
if options.discover: if options.discover:
for cmd, options in tests: for cmd, options in tests:
print (util.getname(cmd, env=options.get('env'), setenv=options.get('setenv'))) print(util.getname(cmd, env=options.get('env'), setenv=options.get('setenv')))
print ('%s tests found.' % len(tests)) print('%s tests found.' % len(tests))
else: else:
run_many(tests, expected=options.expected, failfast=options.failfast) run_many(tests, expected=options.expected, failfast=options.failfast)
......
...@@ -10,6 +10,7 @@ Reproduced on my machine (Linux 3.0.0-16-generic) with backend epoll and select. ...@@ -10,6 +10,7 @@ Reproduced on my machine (Linux 3.0.0-16-generic) with backend epoll and select.
With signalfd enabled (GEVENT_BACKEND=signalfd) it seems to work. With signalfd enabled (GEVENT_BACKEND=signalfd) it seems to work.
""" """
from __future__ import print_function
import gevent import gevent
from contextlib import closing from contextlib import closing
import gc import gc
...@@ -54,7 +55,7 @@ def test_main(): ...@@ -54,7 +55,7 @@ def test_main():
else: else:
pickle.dump(None, done_w) pickle.dump(None, done_w)
except: except:
print 'Uh oh, raised from pickle.' print('Uh oh, raised from pickle.')
traceback.print_exc() traceback.print_exc()
finally: finally:
os._exit(0) os._exit(0)
...@@ -71,7 +72,7 @@ def test_main(): ...@@ -71,7 +72,7 @@ def test_main():
if __name__ == "__main__": if __name__ == "__main__":
print gevent.get_hub() print(gevent.get_hub())
while True: while True:
test_main() test_main()
sys.stderr.write('.') sys.stderr.write('.')
#!/usr/bin/env python #!/usr/bin/env python
"""gevent build & installation script""" """gevent build & installation script"""
from __future__ import print_function
import sys import sys
import os import os
import re import re
...@@ -108,7 +109,7 @@ def make_universal_header(filename, *defines): ...@@ -108,7 +109,7 @@ def make_universal_header(filename, *defines):
if line.startswith(prefix): if line.startswith(prefix):
line = '#ifdef __LP64__\n#define %s 8\n#else\n#define %s 4\n#endif' % (define, define) line = '#ifdef __LP64__\n#define %s 8\n#else\n#define %s 4\n#endif' % (define, define)
break break
print >>f, line print(line, file=f)
f.close() f.close()
......
...@@ -9,6 +9,7 @@ Does the following: ...@@ -9,6 +9,7 @@ Does the following:
- Run set_version.py that will update gevent/__init__.py. - Run set_version.py that will update gevent/__init__.py.
- Run 'python setup.py sdist'. - Run 'python setup.py sdist'.
""" """
from __future__ import print_function
import sys import sys
import os import os
import glob import glob
...@@ -22,7 +23,7 @@ TMPDIR = '/tmp/gevent-make-dist' ...@@ -22,7 +23,7 @@ TMPDIR = '/tmp/gevent-make-dist'
def system(cmd, noisy=True): def system(cmd, noisy=True):
if noisy: if noisy:
print cmd print(cmd)
res = os.system(cmd) res = os.system(cmd)
if res: if res:
sys.exit('%r failed with %s' % (cmd, res)) sys.exit('%r failed with %s' % (cmd, res))
......
#!/usr/bin/python #!/usr/bin/python
from __future__ import print_function
import sys import sys
import re import re
import subprocess import subprocess
...@@ -44,10 +45,10 @@ failed = False ...@@ -44,10 +45,10 @@ failed = False
for line in output: for line in output:
line = line.strip() line = line.strip()
if not is_ignored(line): if not is_ignored(line):
print 'E %s' % line print('E %s' % line)
failed = True failed = True
#else: #else:
# print 'I %s' % line # print('I %s' % line)
if failed: if failed:
sys.exit(1) sys.exit(1)
...@@ -5,6 +5,7 @@ ...@@ -5,6 +5,7 @@
'dev' in __version__ should be replaced with a|b|rc|<empty string> 'dev' in __version__ should be replaced with a|b|rc|<empty string>
""" """
from __future__ import print_function
import sys import sys
import os import os
import re import re
...@@ -150,7 +151,7 @@ def main(): ...@@ -150,7 +151,7 @@ def main():
sys.exit('No differences applied') sys.exit('No differences applied')
else: else:
write(filename, new_content) write(filename, new_content)
print 'Updated %s' % filename print('Updated %s' % filename)
if __name__ == '__main__': if __name__ == '__main__':
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment