Szymon
Szymon

Reputation: 101

Communicating with a Node.js process from Python

I'm trying to start and communicate with a Node.js process from Python. I've tried using subprocess and it keeps hanging on 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)

I've used very similar code previously in order to run shell scripts successfully. I've also checked for running node processes using ps while the above Python script was hanging and it I could see it running. Finally, I've managed to get a valid response via Popen.communicate() instead of readline() but I need to keep the process running for further interaction.

Can someone please advise on how do I spawn and communicate with a Node.js process from Python? It doesn't necessarily need to use subprocess. Thanks.

Upvotes: 1

Views: 937

Answers (2)

Szymon
Szymon

Reputation: 101

Forgot to mention but after a few days I found out that all I needed was -i flag to Node so that it enters the REPL anyway. From node -h:

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

So the code will now look like this:

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

Marking this one as accepted as it doesn't rely on any third party packages.

Upvotes: 1

Lior Cohen
Lior Cohen

Reputation: 5735

I really recommend you work with the higher level pexpect package, instead of the low level stdin /stdout of subprocess.

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

Upvotes: 1

Related Questions