xterm.js实现python终端

需求:在浏览器上有一块python代码编辑块,编辑完后点击运行按钮,后台执行python代码将结果返回给前端展示。

用到的东西:前端用xterm.js  通信用websocket  后端用springboot

问题:如果执行过程中遇到input我要如何跟前端互动?

运行python文件的代码如下(遇到input直接卡了,在idea终端输入值也无效):

proc = Runtime.getRuntime().exec("python "+Path);// 执行py文件
//用输入输出流来截取结果
BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream(),"gb2312"));
String line = null;
while ((line = in.readLine()) != null) {
    //System.out.println(line);
    textArr.add(line);
}
BufferedReader errorin = new BufferedReader(new InputStreamReader(proc.getErrorStream(),"gb2312"));
while ((line = errorin.readLine()) != null) {
    //System.out.println(line);
    errorTextArr.add(line);
}
in.close();
proc.waitFor();

 

 


import subprocess
import threading
import websocket

class StdinThread(threading.Thread):
    def __init__(self, ws):
        threading.Thread.__init__(self)
        self.ws = ws

    def run(self):
        while True:
            input_data = self.ws.recv()
            if input_data is None:
                break
            sys.stdin.write(input_data)
            sys.stdin.flush()

def run_python_code(code):
    # create a websocket connection
    ws = websocket.create_connection("ws://localhost:8080/ws")

    # start a thread to redirect stdin to the websocket connection
    stdin_thread = StdinThread(ws)
    stdin_thread.start()

    # start the python process with stdin redirected to the websocket connection
    process = subprocess.Popen(['python', '-u', '-c', code],
                               stdin=subprocess.PIPE,
                               stdout=subprocess.PIPE,
                               stderr=subprocess.STDOUT)

    # read output from the python process and send it to the websocket connection
    while True:
        output = process.stdout.readline().decode()
        if output == '' and process.poll() is not None:
            break
        if output:
            ws.send(output)

    # cleanup
    stdin_thread.join()
    ws.close()