我正在編寫我自己的python代碼編輯器和終端以獲得樂趣,並在現有程序中實現它以添加scribtability。中止評估python的交互式控制檯
現在我發現,我不知道該怎麼一旦停止運行代碼的評價問題。這怎麼可能完成?
這是我實現:
import code
import contextlib
import sys
from io import StringIO
import copy
@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 PythonTerminal(code.InteractiveConsole):
def __init__(self, shared_vars):
self.shared_vars_start = copy.deepcopy(shared_vars)
self.shared_vars = shared_vars
super().__init__(shared_vars)
self.out_history = []
def run_code(self,code_string):
with capture() as out:
self.runcode(code_string)
self.out_history.append(out)
return out
def restart_interpreter(self):
self.__init__(self.shared_vars_start)
def stop(self):
raise NotImplementedError
if __name__ == '__main__':
a = range(10)
PyTerm = PythonTerminal({'Betrag': a})
test_code = """
for i in range(10000):
for j in range(1000):
temp = i*j
print('Finished'+str(i))
"""
print('Starting')
t = threading.Thread(target=PyTerm.run_code,args=(test_code,))
t.start()
PyTerm.stop()
t.join()
print(PyTerm.out_history[-1]) # This line should be executed immediately and contain an InterruptError
的目標是,評估停止,但該解釋還活着,所以像CTRL + C。
而不是圖像,你可以包含'resetbuffer'和'push'文本嗎?圖像難以搜索並且不適用於屏幕閱讀器,例如爲盲人。謝謝! – darthbith
感謝您的回答,但它並不能真正解決我的問題,因爲代碼的運行評估不會被restbuffer中斷。我將編輯我的答案以顯示原因。 – Jannick