1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
| import threading
import code
import sys
import traceback
import contextlib
from io import StringIO
import copy
EOT = b'\x04'
#from sympy import sympify
try:
import queue
#import builtins
except ImportError:
import Queue as queue
#import __builtin__ as builtins
@contextlib.contextmanager
def capture():
oldout,olderr = sys.stdout, sys.stderr
try:
out=[StringIO(), StringIO()]
sys.stdout,sys.stderr = out
yield out
finally:
sys.stdout,sys.stderr = oldout, olderr
out[0] = out[0].getvalue()
out[1] = out[1].getvalue()
class InteractiveConsole(code.InteractiveConsole):
def __init__(self, inqueue, exitevent,outqueue):
code.InteractiveConsole.__init__(self)
self.inqueue = inqueue
self.outqueue = outqueue
#self.exitevent = exitevent
self.keep_prompting = True
self.stdin = sys.stdin
sys.stdin = self
def readline(self):
'''Implement sys.stdin readline method'''
rl = self.inqueue.get()
if rl == KeyboardInterrupt:
print("KbInterrupt")
raise KeyboardInterrupt()
if rl == EOT:
print("EOT")
self.keep_prompting = False
return rl
def interact(self):
more = 0
try:
while self.keep_prompting:
try:
#self.outqueue.queue.clear()
line = self.raw_input('')
with capture() as out:
more = self.push(line)
self.inqueue.task_done()
self.outqueue.put(out[0])
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
#sys.stdout = self.stdout
def run_interact(*args):
'''Start the"python interpreter" engine'''
iconsole = InteractiveConsole(*args)
iconsole.interact()
#EOT = b'\x04'
inqueue = queue.Queue()
outqueue = queue.Queue()
exitevent = threading.Event()
result=""
proc = threading.Thread(target=run_interact, args=(inqueue, exitevent,outqueue))
proc.start()
#prompt = '...'
def com(x):
try:
inqueue.put(x)
#inqueue.join()
except:
inqueue.put(traceback.format_exc())
return "com : " + outqueue.get(True,3)
def ecrit(x):
return format(x) |
Partager