NodeJS child_process spawn不返回live stdout

yhxst69z  于 8个月前  发布在  Node.js
关注(0)|答案(1)|浏览(115)

我正试图从一个JavaScript文件(在一个electron项目中)中沿着这个python脚本的行沿着运行一些东西,并实时回显输出:

import time

def main():
    print("Hello 1")
    time.sleep(1)
    print("Hello 2")
    time.sleep(1)
    print("Hello 3")

    return 5

if __name__ == "__main__":
    result = main()
    print(f"result: {result}")

字符串
我使用以下JavaScript代码来执行该文件:

// ...

const child = spawn(runners[lang], commandArgs, {shell: true});
child.stdout.setEncoding('utf8');

child.stdout.on('data', (data) => {
    console.log(`Received data: ${data}`);
});


我所看到的是,在整个脚本运行完成后,所有的输出都被打印在一个巨大的blob中,而不是“Hello 1”等逐行发送到我的JavaScript。基本上,似乎我的child.stdout.on回调只运行了一次。这有什么具体的原因吗?如何在python脚本中调用print后立即接收child.stdout.on中的数据?

vxbzzdmp

vxbzzdmp1#

要获得预期的输出,您需要forcibly flush the stdout stream in your python program。这可以通过添加flush=True参数来完成。

import time

def main():
    print("Hello 1", flush=True)
    time.sleep(1)
    print("Hello 2", flush=True)
    time.sleep(1)
    print("Hello 3", flush=True)

    return 5

if __name__ == "__main__":
    result = main()
    print(f"result: {result}", flush=True)

字符串
或者,你可以使用-u选项启动python解释器。这将 * 强制stdout和stderr流不被缓冲 *。这样做,你就不必在每次print函数调用时都指定flush=True

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

const child = spawn("python", ["-u", "your_file_name.py"], {shell: true});
child.stdout.setEncoding('utf8');

child.stdout.on('data', (data) => {
    console.log(`Received data: ${data}`);
});

相关问题