Commit 42a56843 authored by Denis Bilenko's avatar Denis Bilenko

examples: use py3k compatible syntax

parent d212ebb3
...@@ -15,9 +15,9 @@ import urllib2 ...@@ -15,9 +15,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]
......
...@@ -7,6 +7,7 @@ This script splits the job between a number of greenlets to get the ...@@ -7,6 +7,7 @@ This script splits the job between a number of greenlets to get the
results faster. results faster.
""" """
from __future__ import with_statement from __future__ import with_statement
import sys
import gevent import gevent
from gevent import socket from gevent import socket
from gevent.pool import Pool from gevent.pool import Pool
...@@ -22,9 +23,10 @@ def job(url): ...@@ -22,9 +23,10 @@ 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, ex: except socket.gaierror:
print '%s failed with %s' % (url, ex) ex = sys.exc_info()[1]
print ('%s failed with %s' % (url, ex))
finally: finally:
finished += 1 finished += 1
...@@ -33,4 +35,4 @@ with gevent.Timeout(2, False): ...@@ -33,4 +35,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))
...@@ -11,7 +11,7 @@ from gevent.server import StreamServer ...@@ -11,7 +11,7 @@ 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)
# using a makefile because we want to use readline() # using a makefile because we want to use readline()
fileobj = socket.makefile() fileobj = socket.makefile()
fileobj.write('Welcome to the echo server! Type quit to exit.\r\n') fileobj.write('Welcome to the echo server! Type quit to exit.\r\n')
...@@ -19,10 +19,10 @@ def echo(socket, address): ...@@ -19,10 +19,10 @@ def echo(socket, address):
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()
...@@ -34,5 +34,5 @@ if __name__ == '__main__': ...@@ -34,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()
...@@ -2,6 +2,7 @@ ...@@ -2,6 +2,7 @@
[1] http://pypi.python.org/pypi/py-sendfile/ [1] http://pypi.python.org/pypi/py-sendfile/
""" """
from sys import exc_info
from errno import EAGAIN from errno import EAGAIN
from sendfile import sendfile as original_sendfile from sendfile import sendfile as original_sendfile
from gevent.socket import wait_write from gevent.socket import wait_write
...@@ -14,7 +15,8 @@ def gevent_sendfile(out_fd, in_fd, offset, count): ...@@ -14,7 +15,8 @@ def gevent_sendfile(out_fd, in_fd, offset, count):
_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, ex: except OSError:
ex = exc_info()[1]
if ex[0] == EAGAIN: if ex[0] == EAGAIN:
wait_write(out_fd) wait_write(out_fd)
else: else:
......
...@@ -28,8 +28,9 @@ def popen_communicate(args, data=''): ...@@ -28,8 +28,9 @@ def popen_communicate(args, data=''):
try: try:
# p.stdin.write() doesn't return anything, so use os.write. # p.stdin.write() doesn't return anything, so use os.write.
bytes_written += os.write(p.stdin.fileno(), data[bytes_written:]) bytes_written += os.write(p.stdin.fileno(), data[bytes_written:])
except IOError, ex: except IOError:
if ex[0] != errno.EAGAIN: ex = sys.exc_info()[1]
if ex.args[0] != errno.EAGAIN:
raise raise
sys.exc_clear() sys.exc_clear()
socket.wait_write(p.stdin.fileno()) socket.wait_write(p.stdin.fileno())
...@@ -44,7 +45,8 @@ def popen_communicate(args, data=''): ...@@ -44,7 +45,8 @@ def popen_communicate(args, data=''):
if not chunk: if not chunk:
break break
chunks.append(chunk) chunks.append(chunk)
except IOError, ex: except IOError:
ex = sys.exc_info()[1]
if ex[0] != errno.EAGAIN: if ex[0] != errno.EAGAIN:
raise raise
sys.exc_clear() sys.exc_clear()
...@@ -64,10 +66,10 @@ if __name__ == '__main__': ...@@ -64,10 +66,10 @@ if __name__ == '__main__':
# print the results (if available) # print the results (if available)
if job1.ready(): if job1.ready():
print 'finger: %s bytes: %s' % (len(job1.value or ''), repr(job1.value)[:50]) print ('finger: %s bytes: %s' % (len(job1.value or ''), repr(job1.value)[:50]))
else: else:
print 'finger: job is still running' print ('finger: job is still running')
if job2.ready(): if job2.ready():
print 'netstat: %s bytes: %s' % (len(job2.value or ''), repr(job2.value)[:50]) print ('netstat: %s bytes: %s' % (len(job2.value or ''), repr(job2.value)[:50]))
else: else:
print 'netstat: job is still running' print ('netstat: job is still running')
...@@ -51,13 +51,14 @@ def proxy(path, start_response, proxy_url): ...@@ -51,13 +51,14 @@ def proxy(path, start_response, proxy_url):
try: try:
try: try:
response = urllib2.urlopen(path) response = urllib2.urlopen(path)
except urllib2.HTTPError, ex: except urllib2.HTTPError:
response = ex response = sys.exc_info()[1]
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
except Exception, ex: except Exception:
ex = sys.exc_info()[1]
sys.stderr.write('error while reading %s:\n' % path) sys.stderr.write('error while reading %s:\n' % path)
traceback.print_exc() traceback.print_exc()
tb = traceback.format_exc() tb = traceback.format_exc()
......
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