javascript - How do I send stdout in real time from nodejs to angularjs? -
i have script runs long time. generates output. running script nodejs using child_process. how send output of script starts executing , not wait script complete. code have waits script complete , outputs stdout @ once on nodejs console.
sample script:
import time if __name__ == '__main__': in range(5): time.sleep(1) print("hello how " + 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 code ' + code); }); console.log waits script complete , outputs
hello how 1 hello how 2 hello how 3 hello how 4 hello how 5 in 1 shot. there anyway can achieve sending stdout written until child process stops?
the short answer is:
you need reopen
sys.stdoutin non-bufering mode.
example:
import os import sys sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) so program this:
import os import sys import time if __name__ == '__main__': sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) in range(5): time.sleep(1) sys.stdout.write("hello how " + str(i)) sys.stdout.flush()
Comments
Post a Comment