I have a script that runs for a long time. It generates an output. I am running this script from nodejs using child_process. How do I send the output of this script soon as it starts executing and do not wait for the script to complete. The code that I currently have waits for the script to complete and then outputs all the stdout at once on nodejs console.
Sample script:
import time
if __name__ == '__main__':
for i in range(5):
time.sleep(1)
print("Hello how are you " + str(i))
nodejs code:
var spawn = require('child_process').spawn,
ls = spawn('python', ['path/test.py']);
ls.stdout.on('data', function (data) {
console.log('stdout: ' + data);
});
ls.stderr.on('data', function (data) {
console.log('stderr: ' + data);
});
ls.on('close', function (code) {
console.log('child process exited with code ' + code);
});
console.log waits for the script to complete and then outputs
Hello how are you 1
Hello how are you 2
Hello how are you 3
Hello how are you 4
Hello how are you 5
in one shot. Is there anyway I can achieve sending stdout immediately as its written until the child process stops?
flashitimport sysandsys.stdout.flush()after eachprint- befzz