NodeJS child_process spawn 不返回实时标准输出

问题描述 投票:0回答:1

我正在尝试从 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}`);
});

我所看到的是,在整个脚本运行完成后,所有输出都以一个巨大的斑点打印出来,而不是“Hello 1”等被逐行发送到我的javascript。基本上,我的

child.stdout.on
回调似乎只运行一次。这有什么具体原因吗?如何在 python 脚本中调用
child.stdout.on
时立即接收到
print
中的数据?

python node.js ipc child-process spawn
1个回答
0
投票

要获得预期的输出,您需要在Python程序中强制刷新

stdout
。这可以通过添加 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)
    
© www.soinside.com 2019 - 2024. All rights reserved.