NodeJS 有没有办法从child_process.execFile派生的python脚本中获取“实时”输出行,而不用每次都刷新stdout?

htzpubme  于 2023-01-25  发布在  Node.js
关注(0)|答案(3)|浏览(132)

我正在尝试获取一个(“永不结束”)python脚本放入标准输出的行。但是目前我的代码只在python进程退出时才将一些内容记录到控制台。有没有办法可以逐行获取python脚本的“实时”输出?
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脚本时,它可以正常工作

h9a6wy2h

h9a6wy2h1#

更改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刷新到stdout

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');
});
hc8w905p

hc8w905p2#

使用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选项。

gg0vcinb

gg0vcinb3#

尝试在NextJS应用程序中实现类似的东西,并希望从我的python脚本中实时输出,使用python-shell也有同样的问题,即只有当进程存在时才给我输出,我最终使用node-pty代替,这符合预期:

import { spawn } from "node-pty"
const pyProcess = spawn("python", ["path/to/python/script"], {
    name: 'xterm-color',
    cols: 80,
    rows: 30,
    cwd: process.cwd(),
  });

pyProcess.on('data', function (data: { toString: () => any; }) {
  console.log(data.toString());
});

pyProcess.on('exit', (code: any) => {
    console.log(`child process exited with code ${code}`);
  });

相关问题