0

I'm trying to replicate this process to establish communication be nodejs and python through stdin and stdout : https://healeycodes.com/javascript/python/beginners/webdev/2019/04/11/talking-between-languages.html

Context: Sender - which is giving output to stdout

Listener - one who's reading it

Now, when Python is sender and NodeJS is Listener isn't working. NodeJS gives no output. On further digging my issue is very similar to Not receiving stdout from nodejs spawned process except I don't need unbuffered output as such. Tried sol from last ques.. didn't work.

Here are files: sensor.py

import random, time
import sys

time.sleep(random.random() * 5)  # wait 0 to 5 seconds
temperature = (random.random() * 20) - 5  # -5 to 15
print(temperature, flush=True, end='')
sys.stdout.flush()

listener.js

const { spawn } = require('child_process');

//spawn()
const child = spawn('python', ['path-to-sensor.py']);
console.log('Here');

child.stdout.on('data', function(data) {
    console.log('Got the data')
    console.log(data)
  });
  child.on('error', function () {
    console.log("Failed to start child.");
  });
  child.on('close', function (code) {
    console.log('Child process exited with code ' + code);
  });
  child.stdout.on('end', function () {
    console.log('Finished collecting data chunks.');
  });

Reason: Event listener - child.stdout.on('data', callback) is never called

What I want the output to be: Store the stdout from sensor.py in a variable

Can't figure out what else I can do to fix this

1 Answers1

0

In sensor.py you are not using the right syntax in your code:

print(temperature, flush=True, end='')

The right syntax is:

print(object(s), sep=separator, end=end, file=file, flush=flush)

Source

If you left the code in sensor.py as:

print(temperature)

And in listener.js as:

child.stdout.on('data', function(data) {
    console.log('Got the data')
    //console.log(data)
    console.log(data.toString('utf8'))
 });

It works ok

ManuelMB
  • 1,254
  • 2
  • 8
  • 16