有没有办法从 child_process.execFile 生成的 python 脚本中获取 'live' 输出行,而无需每次都刷新标准输出?

Is there a way to get 'live' output lines from a python script spawned by child_process.execFile without flushing stdout every time?

我正在尝试将 ('never ending') python 脚本放入 stdout 的行。但目前我的代码只会在 python 进程退出时将某些内容记录到控制台。有没有办法逐行获取 python 脚本的 'live' 输出?

spawn_child.js:

let execFile = require("child_process").execFile;

var child = execFile("python3", ["PATH_TO_FILE"]);

child.stdout.on("data", data=>{
    console.log(data.toString());
});
child.stderr.on("data", data=>{
    console.log(data.toString());
});
child.on("exit", code=>{
    console.log("Child exited with code "+code);
});

python 文件:

from time import sleep

while True:
    sleep(3)
    print("test")

编辑:它在使用 nodejs 脚本而不是 python 脚本时有效

将 python 脚本更改为

import time
import sys

while True:
    time.sleep(1)
    print("test")
    sys.stdout.flush()

并增加子进程的缓冲区大小

const child = execFile("python", ["./runner.py"], {
    detached: true,
    maxBuffer: 10 * 1024 * 1024 * 1024
});

或者您可以在不使用 python-shell

刷新到标准输出的情况下执行此操作
const { PythonShell } = require('python-shell');

let pyshell = new PythonShell('runner.py');
    
pyshell.on('message', function (message) {
    console.log(message);
});

pyshell.end(function (err, code, signal) {
    if (err) throw err;
    console.log('The exit code was: ' + code);
    console.log('The exit signal was: ' + signal);
    console.log('finished');
});

使用 spawn 而不是 execFile,不要忘记选项 shellstdio

const spawn = require("child_process").spawn;

const child = spawn("python3", ["file.py"], {shell: true, stdio: 'inherit'});

child.on('data', function(data) {
    console.log(data);
});
  
child.on('close', function(code) {
    console.log('Child process exited with exit code '+code);
});

您还可以添加 cwd 选项。