小编Yog*_*tia的帖子

使用 websocket 实时流 stdout 和 stdin

在线编译器这是我的网站,用户可以在其中运行控制台程序。

目前,用户在运行程序之前必须输入程序输入。我正在尝试为该程序构建实时用户输入(希望提供与他们在笔记本电脑上运行程序相同的体验)。

在实现这一目标的研究中,我遇到了一种使用websocket流式传输 stdout 和 stdin 的解决方案。

我的实现

# coding: utf-8
import subprocess
import thread

from tornado.websocket import WebSocketHandler

from nbstreamreader import NonBlockingStreamReader as NBSR


class WSHandler(WebSocketHandler):
    def open(self):
        self.write_message("connected")
        self.app = subprocess.Popen(['sh', 'app/shell.sh'], stdout=subprocess.PIPE, stdin=subprocess.PIPE,
                                    shell=False)
        self.nbsr = NBSR(self.app.stdout)
        thread.start_new_thread(self.soutput, ())

    def on_message(self, incoming):
        self.app.stdin.write(incoming)

    def on_close(self):
        self.write_message("disconnected")

    def soutput(self):
        while True:
            output = self.nbsr.readline(0.1)
            # 0.1 secs to let the shell output the result
            if not output:
                print 'No more data'
                break
            self.write_message(output)
Run Code Online (Sandbox Code Playgroud)

nbstreamreader.py …

python websocket python-2.7

2
推荐指数
1
解决办法
3791
查看次数

标签 统计

python ×1

python-2.7 ×1

websocket ×1