我正在尝试将一个(‘永不结束’) python脚本放入stdout的代码行。但目前,我的代码仅在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脚本时,它可以工作
发布于 2021-04-18 03:42:38
将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');
});发布于 2021-04-18 03:48:28
使用spawn而不是execFile,不要忘记选项shell和stdio。
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选项。
https://stackoverflow.com/questions/67141936
复制相似问题