与来自 Python 的 Node.js 进程通信

Communicating with a Node.js process from Python

我正在尝试启动 Python 的 Node.js 进程并与之通信。我试过使用 subprocess,它一直挂在 out = p.stdout.readline()

p = subprocess.Popen(
    ["node"],
    stdin=subprocess.PIPE,
    stdout=subprocess.PIPE,
)
msg = "console.log('this is a test');"
p.stdin.write(msg.encode("utf-8"))
p.stdin.write(b"\n")
p.stdin.flush()
out = p.stdout.readline()
print(out)

为了 运行 shell 脚本成功,我之前使用过非常相似的代码。当上面的 Python 脚本挂起时,我还使用 ps 检查了 运行ning node 进程,我可以看到它 运行ning。最后,我设法通过 Popen.communicate() 而不是 readline() 获得了有效响应,但我需要保留进程 运行ning 以进行进一步交互。

有人可以建议我如何从 Python 生成 Node.js 进程并与之通信吗?它不一定需要使用subprocess。谢谢。

我真的建议你使用更高级别的 pexpect 包,而不是子进程的低级别标准输入/标准输出。

import pexpect
msg = "console.log('this is a test');"
child = pexpect.spawn('node')
child.expect('.*')
child.sendline(msg)
...

忘了提,但几天后我发现我所需要的只是 -i 标记 Node 以便它无论如何都能进入 REPL。来自 node -h:

-i, --interactive        always enter the REPL even if stdin does not appear to be a terminal

所以代码现在看起来像这样:

p = subprocess.Popen(
    ["node", "-i"],
    stdin=subprocess.PIPE,
    stdout=subprocess.PIPE,
)

将此标记为已接受,因为它不依赖于任何第三方包。