与Python中的Node.js进程通信



我正在尝试从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运行node进程的情况,我可以看到它在运行。最后,我已经设法通过Popen.communicate()而不是readline()获得了有效的响应,但我需要保持进程的运行以进行进一步的交互。

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

我真的建议您使用更高级别的pexpect包,而不是子流程的低级别stdin/stdout。

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

忘记提了,但几天后我发现我所需要的只是Node的-i标志,这样它就可以进入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,
)

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

最新更新