import threading import code import sys import traceback try: import queue except ImportError: import Queue as queue class InteractiveConsole(code.InteractiveConsole): def __init__(self, inqueue, exitevent): code.InteractiveConsole.__init__(self) self.inqueue = inqueue self.keep_prompting = True self.stdin = sys.stdin sys.stdin = self def readline(self): rl = self.inqueue.get() return rl def interact(self): more = 0 try: while self.keep_prompting: try: line = self.raw_input('') more = self.push(line) except KeyboardInterrupt: self.write("\nKeyboardInterrupt\n") self.resetbuffer() more = 0 except SystemExit: self.exitevent.set() except: print('INTERACT\n') traceback.print_exc() self.resetbuffer() more = 0 finally: sys.stdin = self.stdin def run_interact(*args): '''Start the"python interpreter" engine''' iconsole = InteractiveConsole(*args) iconsole.interact() inqueue = queue.Queue() exitevent = threading.Event() proc = threading.Thread(target=run_interact, args=(inqueue, exitevent)) proc.start() def com(x): try: a = inqueue.put(x) except: a = inqueue.put(traceback.format_exc()) return str(a)