daizeyang2017 2021-01-23 11:16 采纳率: 0%
浏览 204

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();

 

  • 写回答

1条回答 默认 最新

  • Kwan的解忧杂货铺 Java领域优质创作者 2023-04-17 16:47
    关注
    
    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()
    
    
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题:求帮写python代码
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?