I'm writing a Sublime Text plugin that provides multiple Python shells accessible via UNIX sockets. Each shell should act as a standalone REPL running on its own thread. (It is undesirable for these shells to have their own processes; sharing a single process is an absolute requirement.)
The builtin exec() function prints output to stdout if the code was compiled with mode='single' and is an expression that does not evaluate to None. I need to send this output over the socket instead.
I know that this can be done by patching stdout. However, this would not work here because multiple consoles may be running in multiple threads (plus the built-in console).
My ideas are as follows:
- Try to
compile()the input withmode='eval',eval()it, and print the result (if not None). If it won't compile, trymode='exec'instead ofmode='single'. - For each console's thread, keep the output stream in thread-local storage. Patch
sys.stdoutwith an object that checks for these streams before calling "regular" stdout. - Somehow provide a patched
systo each console.
These don't seem like great ideas. Is there a better one?
execdoesn't auto-print expression values.)mode='single', which I forgot to mention (now in the question). I'm aware that it won't be perfect, but I'm willing to settle for a definition of "reasonably good" that includes echoing the output.mode='single', yeah, you'd get autoprinting.