简体   繁体   English

我如何从nodejs实时发送stdout到angularjs?

[英]How do I send stdout in real time from nodejs to angularjs?

I have a script that runs for a long time. 我的脚本可以运行很长时间。 It generates an output. 它产生一个输出。 I am running this script from nodejs using child_process. 我正在使用child_process从nodejs运行此脚本。 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. 我当前拥有的代码等待脚本完成,然后在nodejs控制台上一次输出所有标准输出。

Sample script: 示例脚本:

import time

if __name__ == '__main__':
    for i in range(5):
        time.sleep(1)
        print("Hello how are you " + str(i))

nodejs code: nodejs代码:

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 console.log等待脚本完成,然后输出

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? 无论如何,在子进程停止之前,我可以立即完成写的标准输出吗?

The short answer is: 简短的答案是:

You need to reopen sys.stdout in non-bufering mode. 您需要以非同步模式重新打开sys.stdout

Example: 例:

import os
import sys

sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)

So your program would look like this: 因此,您的程序将如下所示:

import os
import sys
import time

if __name__ == '__main__':
    sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)

    for i in range(5):
        time.sleep(1)
        sys.stdout.write("Hello how are you " + str(i))
        sys.stdout.flush()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM