首页 > 解决方案 > Popen stdin 在 cmd shell 中有效,但在 jupyter 中无效

问题描述

当我使用代码运行以下代码时python test.py。另一个控制台窗口出现,写入hello world并等待关闭。但是当我使用 Jupyter 并在一个单元格中执行整个代码时,“hello world”永远不会出现在新控制台窗口的屏幕上。

我虽然可能存在一些缓冲问题,但文档指出 stdin 不受任何缓冲的影响。从我使用的 Jupyter 端flush(),应该立即发送消息。stdin的进程连接到,PIPE所以程序应该看到消息。

有人可以帮我将消息发送到新窗口stdin吗?

如何打开一个新的控制台窗口的最初想法来自这篇文章:How can I open two consoles from a single script

from subprocess import Popen, PIPE, CREATE_NEW_CONSOLE
import sys

command = [
    sys.executable,
    "-u",
    "-c",
    """import sys
for line in sys.stdin:
    sys.stdout.write(line)
    sys.stdout.flush()
input()
""",
]
proc = Popen(
    command,
    stdin=PIPE,
    bufsize=1,
    universal_newlines=True,
    creationflags=CREATE_NEW_CONSOLE,
)
proc.stdin.write("hello world\n")
proc.stdin.flush()
proc.wait()

标签: pythonjupyterpopen

解决方案


推荐阅读