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