为什么 subprocess.Popen 在打开 gnugo 时挂起?

Why does subprocess.Popen hang when opening gnugo?

我正在尝试围绕着名的 Go 程序 GnuGo 编写一个 python 包装器。我的方法(我不确定这是否可行)是使用子进程模块的 Popen 在 GTP(go 文本协议模式)中启动 GnuGo。在解释器中它看起来像这样

>>> import subprocess
>>> game = subprocess.Popen(['gnugo', '--mode', 'gtp'])
>>>

然后解释器挂起,但没有完全挂起。如果我稍等片刻,我可以让大约每三次击键出现在命令行上。如果我使用 shell=True 参数,那么 GnuGo 将以 ASCII 模式启动,如下所示:

    A B C D E F G H J K L M N O P Q R S T
 19 . . . . . . . . . . . . . . . . . . . 19
 18 . . . . . . . . . . . . . . . . . . . 18
 17 . . . . . . . . . . . . . . . . . . . 17
 16 . . . + . . . . . + . . . . . + . . . 16
 15 . . . . . . . . . . . . . . . . . . . 15
 14 . . . . . . . . . . . . . . . . . . . 14
 13 . . . . . . . . . . . . . . . . . . . 13
 12 . . . . . . . . . . . . . . . . . . . 12
 11 . . . . . . . . . . . . . . . . . . . 11
 10 . . . + . . . . . + . . . . . + . . . 10
  9 . . . . . . . . . . . . . . . . . . .  9
  8 . . . . . . . . . . . . . . . . . . .  8
  7 . . . . . . . . . . . . . . . . . . .  7
  6 . . . . . . . . . . . . . . . . . . .  6
  5 . . . . . . . . . . . . . . . . . . .  5
  4 . . . + . . . . . + . . . . . + . . .  4
  3 . . . . . . . . . . . . . . . . . . .  3
  2 . . . . . . . . . . . . . . . . . . .  2
  1 . . . . . . . . . . . . . . . . . . .  1
    A B C D E F G H J K L M N O P Q R S T

black(1):

在 GTP 模式下,GnuGo 启动并等待一些输入而不向终端打印任何内容。

谁能解释一下为什么会这样?

问题是 gnugo 和 python 解释器都试图从同一个终端读取。

您需要将 stdin=subprocess.PIPE 参数传递给 Popen 调用,然后您可以将程序的输入写入其标准输入:

import subprocess
game = subprocess.Popen(['gnugo', '--mode', 'gtp'], stdin=subprocess.PIPE)
game.stdin.write(b"...")
...