【问题标题】:Node Child Process (Spawn) is not returning data correctly when using with function与函数一起使用时,节点子进程(Spawn)未正确返回数据
【发布时间】:2021-12-10 17:02:57
【问题描述】:

我正在尝试根据我的 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 代码。

【问题讨论】:

    标签: javascript python node.js function spawn


    【解决方案1】:

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

    您可能希望使用 new Promise() 封装您的子进程管理(您将需要它,因为 child_process 是回调异步 API,并且您需要 promise-async 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;
    }
    
    

    【讨论】:

    • 仍然无法查看此屏幕截图打印空白Image .PS - generateCanadaScore 函数正确输出 const 打印数据
    • @Vaibhavdadhich 如果对您有帮助,请确保接受他的回答,以便其他人知道这是解决类似问题的可行解决方案。
    • 您没有显示任何将函数连接到请求处理程序的代码,您只是在应用程序启动后调用它一次。我怀疑这就是你想要的 API。
    • 非常感谢@AKX 它在与请求处理程序挂钩时工作,现在出于好奇我的问题是为什么它在与 app.listen 一起使用时不起作用?
    • 因为 app.listen 回调只是为了知道应用何时在监听,仅此而已。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多