使用 with 函数时,节点子进程 (Spawn) 未正确返回数据

Node Child Process (Spawn) is not returning data correctly when using with function

我正在尝试根据我的 python 脚本的输出生成新乐谱。 python 脚本 return 正确输入数据和正确打印 JS 程序 但问题是当我 return 值并打印它时,它显示 undefined

函数代码-

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 事件处理程序。 (它 returns undefined,所以你基本上是在做 await Promise.resolve(undefined),什么都不等待)。

您可能希望使用 new Promise() 包装您的子进程管理(您需要它,因为 child_process 是回调异步 API,并且您需要 promise-async APIs):

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;
}