Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

357
Views
How to implement two-way communication between nodejs and a python subprocess

I've got a node.js application that needs to pass input to a python program and get the input back. This process needs to occur frequently and with as little latency as possible. Thus I've chosen to use the child_process package. The javascript code is below

child_process = require('child_process');

class RFModel {

    constructor () {

        this.answer = null;
        this.python = child_process.spawn('python3', ['random_forest_model.py']);

        this.python.stdout.on('data', (data)=>{
            this.receive(data);
        });
        
    }

    send (data) {
        this.answer = null;
        this.python.stdin.write(data);
    }

    receive (data) {
        data = data.toString('utf8')
        console.log(data)
        this.answer = data;
    }

}

const model = new RFModel()

function timeout(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}
(async ()=>{
    await timeout(7000)
    model.send('asdf')
})();

And this is the python code:

import sys

sys.stdout.write('test')
sys.stdout.flush()

for line in sys.stdin:
    open("test.txt", "a") #janky test if input recieved

    sys.stdout.write(line)
    sys.stdout.flush()

The nodejs process receives the first "test" output from the python process, but it does not seem like python is receiving any input from nodejs, since there is no echo or text file being created. What am I doing wrong?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

I'm not a python expert, but presumably, for line in sys.stdin: is expecting an actual line (a series of characters followed by a line break character). But, from your nodejs program you aren't sending a line break character. You're just sending a series of characters. So your Python program is still waiting for the line break character to signify the end of the line.

Try changing this:

model.send('asdf')

to this:

model.send('asdf\n')

When I run it now with this change, I get this output:

test
asdf

Where there's a delay before the asdf shows up.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!