从Python与Node.js进程通信

2024-04-24 09:59:49 发布

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

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


Tags: 脚本nodereadline进程stdinstdoutjsmsg
2条回答

忘了提了,但几天后我发现我所需要的只是节点的-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,
)

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

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

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

相关问题 更多 >