小编ca4*_*221的帖子

在 Python 中流式传输标准输入/标准输出

我正在尝试向/从简单的 WebSockets UI 流式传输 bash shell,但是我在重定向 IO 时遇到了问题。我想启动一个 bash 实例并将 stdout 和 stdin 连接到与我的 Web UI 交互的 write_message() 和 on_message() 函数。这是我正在尝试做的简化版本:

class Handler(WebSocketHandler):
    def open(self):
        print "New connection opened."
        self.app = subprocess.Popen(["/bin/bash", "--norc", "-i"], stdout=subprocess.PIPE, stdin=subprocess.PIPE, shell=False)
        thread.start_new_thread(self.io_loop, ())

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

    def on_close(self):
        self.app.terminate()

    def io_loop(self):
        while self.app.poll() is None:
            line = self.app.stdout.readline()
            if line:
                self.write_message(line)
Run Code Online (Sandbox Code Playgroud)

虽然 bash 似乎启动并且 on_message 确实被调用,但我没有得到任何输出。readline() 仍然阻塞。我尝试过 stdout.read()、stdout.read(1) 和各种缓冲区修改,但仍然没有输出。我还尝试在 on_message 中使用尾随 '\n' 的硬编码命令来隔离问题,但我仍然没有从 readline() 得到任何输出。

理想情况下,我想实时流式传输写入 stdout 的每个字节,而无需等待 EOL 或任何其他字符,但我很难找到正确的 API。任何指针将不胜感激。

python tornado websocket

5
推荐指数
1
解决办法
2388
查看次数

标签 统计

python ×1

tornado ×1

websocket ×1