python - 中止 python 交互式控制台的评估

标签 python standard-library

为了好玩,我正在编写自己的 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。

最佳答案

尝试:

def stop(self):
    self.resetbuffer()#abort currently executing code by wiping the input buffer 
    self.push("exit()")#trigger an exit from the interpreter 

这两个方法的用法如下:

|  push(self, line)
|      Push a line to the interpreter.
|      
|      The line should not have a trailing newline; it may have
|      internal newlines.  The line is appended to a buffer and the
|      interpreter's runsource() method is called with the
|      concatenated contents of the buffer as source.  If this
|      indicates that the command was executed or invalid, the buffer
|      is reset; otherwise, the command is incomplete, and the buffer
|      is left as it was after the line was appended.  The return
|      value is 1 if more input is required, 0 if the line was dealt
|      with in some way (this is the same as runsource()).

 |  resetbuffer(self)
 |      Reset the input buffer.

关于python - 中止 python 交互式控制台的评估,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42445167/

相关文章:

python - 在文件中搜索字符串的有效方法

python - 从集合python中获取项目

c++ - Linux C++ LD_LIBRARY_PATH 抑制标准库

c++ - 使用 std::inner_product 时内积为零

C StdLib malloc 来自 (N)ASM

python - 盈透证券Python API连接缓冲区

Python subprocess.Popen 不接受文本参数

c - 有没有办法在不包含 <complex.h> 的情况下声明复数?

c++ - 为什么使用 push_back() 分配时 vector 元素的地址不连续?

python - 无法通过 python 连接到 ssh