Skip to content

Commit

Permalink
Replaced print with print_function from __future__, refs gevent#38.
Browse files Browse the repository at this point in the history
  • Loading branch information
fantix authored and denik committed Dec 23, 2013
1 parent c412d47 commit 08570bf
Show file tree
Hide file tree
Showing 53 changed files with 218 additions and 172 deletions.
4 changes: 2 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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

Expand Down
2 changes: 1 addition & 1 deletion benchmarks/micro.sh
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#!/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()'
Expand Down
3 changes: 2 additions & 1 deletion doc/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -19,7 +20,7 @@
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:
Expand Down
11 changes: 6 additions & 5 deletions doc/generate_rst.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#!/usr/bin/env python
from __future__ import print_function
import os
import glob
from os.path import join, dirname, abspath, basename
Expand All @@ -21,7 +22,7 @@
'''

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('_'))
Expand Down Expand Up @@ -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):
Expand All @@ -83,10 +84,10 @@ def iter_autogenerated():
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()
Expand Down
13 changes: 7 additions & 6 deletions doc/mysphinxext.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from __future__ import print_function
from sphinx.ext.autodoc import cut_lines
from sphinx.ext import intersphinx
from docutils import nodes
Expand Down Expand Up @@ -34,28 +35,28 @@ def new_reference(refuri, reftitle):
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:
assert stripped_aliasname[0] == '.', repr(stripped_aliasname)
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':
Expand Down
2 changes: 1 addition & 1 deletion doc/servers.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 3 additions & 2 deletions examples/concurrent_download.py
Original file line number Diff line number Diff line change
Expand Up @@ -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']

Expand All @@ -15,9 +16,9 @@


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]

Expand Down
7 changes: 4 additions & 3 deletions examples/dns_mass_resolve.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
GEVENT_RESOLVER=thread python dns_mass_resolve.py
"""
from __future__ import print_function
from __future__ import with_statement
import gevent
from gevent import socket
Expand All @@ -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

Expand All @@ -36,4 +37,4 @@ def job(url):
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))
11 changes: 6 additions & 5 deletions examples/echoserver.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,32 +6,33 @@
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__':
# to make the server use SSL, pass certfile and keyfile arguments to the constructor
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()
2 changes: 1 addition & 1 deletion examples/geventsendfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
9 changes: 5 additions & 4 deletions examples/processes.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#!/usr/bin/env python
from __future__ import print_function
import gevent
from gevent import subprocess

Expand All @@ -11,10 +12,10 @@

# 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')
3 changes: 2 additions & 1 deletion examples/psycopg2_pool.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from __future__ import print_function
from __future__ import with_statement
import sys
import contextlib
Expand Down Expand Up @@ -153,4 +154,4 @@ def create_connection(self):
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)
3 changes: 2 additions & 1 deletion examples/threadpool.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from __future__ import print_function
import time
import gevent
from gevent.threadpool import ThreadPool
Expand All @@ -9,4 +10,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)
5 changes: 3 additions & 2 deletions examples/udp_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,15 @@
There's nothing gevent-specific here.
"""
from __future__ import print_function
import sys
from gevent import socket

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 changes: 3 additions & 2 deletions examples/udp_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,17 @@
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()
5 changes: 3 additions & 2 deletions examples/unixsocket_client.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
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()
3 changes: 2 additions & 1 deletion examples/webchat/run_standalone.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#!/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()
7 changes: 4 additions & 3 deletions examples/webproxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -97,7 +98,7 @@ def fix_link_cb(m):
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)
Expand All @@ -122,5 +123,5 @@ def fix_link_cb(m):

if __name__ == '__main__':
from gevent.pywsgi import WSGIServer
print 'Serving on %s...' % LISTEN
print('Serving on %s...' % LISTEN)
WSGIServer(LISTEN, application).serve_forever()
5 changes: 3 additions & 2 deletions examples/webpy.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#!/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
Expand All @@ -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()
3 changes: 2 additions & 1 deletion examples/wsgiserver.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#!/usr/bin/python
"""WSGI server example"""
from __future__ import print_function
from gevent.pywsgi import WSGIServer


Expand All @@ -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()
Loading

0 comments on commit 08570bf

Please sign in to comment.