节点子进程(Spawn)在使用函数时没有正确返回数据



我正在尝试根据我的python脚本的输出生成一个新的分数。python脚本正确返回数据,JS程序正确打印但问题是,当我返回值并打印它时,它显示未定义

功能代码-

async function generateCanadaScore(creditscore = 0) {
console.log(creditscore, "creditscore"); //prints 300
let MexicoData = 0;
const python = spawn("python", [
"cp_production.py",
"sample_dill.pkl",
"mexico",
Number(creditscore),
]);
await python.stdout.on("data", function (data) {
console.log("Pipe data from python script ...");
console.log(data.toString()); //prints number 
MexicoData = data.toString();
console.log(MexicoData) // prints number
//working fine till here printing MexicoData Correctly (Output from py file) , problem in return
return MexicoData ;
});
python.stderr.on("data", (data) => {
console.log(data); // this function doesn't run
});
// return MexicoData ; already tried by adding return statement here still same error
}

呼叫功能码-

app.listen(3005, async () => {
console.log("server is started");
//function calling 
// Only for testing purpose in listen function 
let data = await generateCanadaScore(300);
console.log(data, "data"); // undefined
});

我不能分享python代码,因为这是机密。

您不能在事件处理程序上await。(它返回undefined,所以你基本上在做await Promise.resolve(undefined),它什么都不等待)。

你可能想用new Promise()包装你的子进程管理(你需要,因为child_process是一个回调异步API,你需要承诺异步API):

const {spawn} = require("child_process");
function getChildProcessOutput(program, args = []) {
return new Promise((resolve, reject) => {
let buf = "";
const child = spawn(program, args);
child.stdout.on("data", (data) => {
buf += data;
});
child.on("close", (code) => {
if (code !== 0) {
return reject(`${program} died with ${code}`);
}
resolve(buf);
});
});
}
async function generateCanadaScore(creditscore = 0) {
const output = await getChildProcessOutput("python", [
"cp_production.py",
"sample_dill.pkl",
"mexico",
Number(creditscore),
]);
return output;
}

相关内容

  • 没有找到相关文章

最新更新