scgi-test: update byte/string handling for Python 2/3 compatability.
authorW. Trevor King <wking@tremily.us>
Sat, 29 Sep 2012 13:24:12 +0000 (09:24 -0400)
committerW. Trevor King <wking@tremily.us>
Sat, 29 Sep 2012 13:24:12 +0000 (09:24 -0400)
posts/SCGI/scgi-test.py

index 4f6ea3d152300e834fe2516980d819afa578d437..36e5b178afd8c714a7d677d14888afb162c04f2a 100755 (executable)
@@ -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)