From: W. Trevor King Date: Sat, 29 Sep 2012 13:24:12 +0000 (-0400) Subject: scgi-test: update byte/string handling for Python 2/3 compatability. X-Git-Url: http://git.tremily.us/?a=commitdiff_plain;h=56552cdb42275c8984e1f49ce09ca4e0abc6753d;p=blog.git scgi-test: update byte/string handling for Python 2/3 compatability. --- diff --git a/posts/SCGI/scgi-test.py b/posts/SCGI/scgi-test.py index 4f6ea3d..36e5b17 100755 --- a/posts/SCGI/scgi-test.py +++ b/posts/SCGI/scgi-test.py @@ -20,6 +20,7 @@ """ import socket as _socket +import sys as _sys try: # Python 3 import urllib.parse as _urllib_parse except ImportError: # Python 2 @@ -92,11 +93,14 @@ def recvall(socket): if not r: break ret.append(r) - return ''.join(ret) + return b''.join(ret) def request(socket, data=None, **kwargs): """Send a request and return the response string.""" - socket.sendall(netstring(header(data=data, **kwargs))) + ns = netstring(header(data=data, **kwargs)) + if _sys.version_info >= (3, 0): # Python 3 + ns = ns.encode('ascii') + socket.sendall(ns) if data: socket.sendall(data) return recvall(socket) @@ -125,4 +129,7 @@ if __name__ == '__main__': finally: socket.close() if response: - sys.stdout.write(response) + if _sys.version_info >= (3, 0): # Python 3 + sys.stdout.buffer.write(response) + else: + sys.stdout.write(response)