I would like to have an interactive console in a single-threaded script that has several TCP connections open. This means I can't just have a standard input blocking the thread.
Is there an easy way to do this? Or should I just put the console in its own thread and be done with it?
You can subclass InteractiveConsole (from the builtin 'code' module) and override the push() method with a wrapper that redirects stdout/stderr to a StringIO instance before forwarding to the base InteractiveConsole's push() method. Your wrapper can return a 2-tuple (more, result) where 'more' indicates whether InteractiveConsole expects more input, and 'result' is whatever InteractiveConsole.push() wrote to your StringIO instance.
It sounds harder than it is. Here's the basic premise:
Check out this complete example, which accepts input from a UDP socket:
Start two consoles and run server.py in one, client.py in the other. What you see in client.py should be indistinguishable from python's regular interactive interpreter, even though all commands are being round-tripped to server.py for evaluation.
Of course, using sockets like this is terribly insecure, but it illustrates how to evaluate an external input asynchronously. You should be able to adapt it to your situation, as long as you trust the input source. Things get 'interesting' when someone types:
But that's another problem entirely... :-)
Either single-threaded or multi-threaded will do, but if you choose not to use threads, you will need to use polling (in C this may be done using poll(2), for example) and check for whether the console and/or the TCP connections have input ready.