no newlines for python interactive console over socket
Question: In a C program embedding the python interpreter, I spawn a python interactive
console over a TCP socket.

    
    
    import socket
    import code
    import sys
    
    s = socket.socket()
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind(('0.0.0.0', 2000))
    s.listen(1)
    c = s.accept()[0] # client socket
    
    def sread(s, len):
            return s.recv(len)
    def swrite(s, str):
            return s.sendall(str)
    def sreadline(s):
            return sread(s, 256) # lazy implementation for quick testing
    socket.socket.read = sread
    socket.socket.write = swrite
    socket.socket.readline = sreadline
    sys.stdin = c
    sys.stdout = c
    sys.stderr = c
    code.interact() # runs the interactive console
    

This basically works. But, the interactive console never ever issues any end-
of-line character when returning the result of some user input statement. In
other words we get things like this:

    
    
    nc localhost 2000
    Python 2.7.3 (default, Sep 26 2012, 21:53:55) 
    [GCC 4.7.2] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    (InteractiveConsole)
    >>> 1+1
    2>>> 
    

We see no CR-LF after the result '2' send by the interpreter in response to
the user input '1+1', and before the next prompt '>>>'. The absence of any
end-of-line character (CR and/or LF) is confirmed by examining the output of
the user end of the socket in hexadecimal, or examining the string that is
about to be written to the socket in function swrite().

Now why are no end-of-line characters issued by the interactive console?

Can it be fixed and how?


Answer: The question about the 'why' is still open, but as to how to fix it, here is
solution. Instead of adding read/write/readline methods to the socket.socket
class, make a wrapper of the socket.socket class:

    
    
    import socket
    import code
    import sys
    
    s = socket.socket()
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind(('0.0.0.0', 2000))
    s.listen(1)
    c = s.accept()[0] # client socket
    
    class sw: # socket wrapper
        def __init__(self, s):
            self.s = s
        def read(self, len):
                return self.s.recv(len)
        def write(self, str):
                return self.s.send(str)
        def readline(self):
                return self.read(256) # lazy implementation for quick testing
    c = sw(c)
    sys.stdin = c
    sys.stdout = c
    sys.stderr = c
    code.interact() # runs the interactive console
    

Now this works as expected, but for an unknown reason.

    
    
    nc localhost 2000
    Python 2.7.3 (default, Sep 26 2012, 21:51:14) 
    [GCC 4.7.2] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    (InteractiveConsole)
    >>> 1+1
    2
    >>>
    

