简体   繁体   English

如何创建一个通用的 JavaScript 函数,它可以运行 python 脚本并以 json 格式返回数据(如果有)?

[英]How to create a generalized JavaScript function that can run python scripts and return data in json format if any?

What I am currently able to do我目前能够做什么

const { spawn } = require("child_process");

exports.fetchWeatherdata = (location) => {
  console.log("DIR NAME DB" + __dirname)
  return new Promise((resolve, reject) => {
    let buf = "";
    const python = spawn("python", [
      __dirname + "/weathergetter.py",
      location.toString(),
    ]);

    python.stdout.on("data", (data) => {
      buf += data;
    });

    python.stderr.on("data", (data) => {
      console.error(`stderr: ${data}`);
    });

    python.on("close", (code) => {
      if (code !== 0) {
        return reject(`child process died with ${code}`);
      }
      const dataToSend = JSON.parse(buf.toString().replace(/\'/g, '"'));
      return resolve(dataToSend);
    });
  });
};


//in another file
const { fetchWeatherdata } = require('../python/weather')
exports.sendData = (req, res) => {
    console.log(req.query)
    console.log(req.params)

    async function main() {
        var wea = await fetchWeatherdata(req.params.loc);
        // console.log(wea);
        res.send(wea)
    }
    main()
}



What I want to achieve我想要达到的目标

const { spawn } = require("child_process");

exports.pythonFileRunner = (pathToFile, arguments) => {
   // some code goes here. This is where I need help
   return "output of the python file 📂"
}

//in another file
const { pythonFileRunner } = require('../python/weather')

exports.fetchWeatherdata = (location) => {
   //something like this ↓↓↓
   data = pythonFileRunner("path/to/file/main.py", location)
   return data
}

Basically, I want to create a function that can run any given python file with or without arguments and return its output.基本上,我想创建一个函数,该函数可以带或不带参数运行任何给定的 python 文件并返回其输出。
Please Note : I want to finish all the async-await stuff inside the pythonFileRunner() function.请注意:我想完成pythonFileRunner()函数中的所有async-await内容。 This function must return only the output, which I can modify according to my usecase这个函数必须只返回输出,我可以根据我的用例修改它

If I am taking the wrong approach, please let me know in the comments.如果我采取了错误的方法,请在评论中告诉我。

It should be basically the same.应该是基本一样的。 Just replace只需更换

    const python = spawn("python", [
      __dirname + "/weathergetter.py",
      location.toString(),
    ]);

with

    const python = spawn("python", [
      pathToFile,
      ...arguments
    ]);

I have modified the fetchweatherdata function little to get what I wanted.我几乎没有修改 fetchweatherdata 函数以获得我想要的。

const { spawn } = require("child_process");

function pythonRunner(path, arguments) {
    return new Promise((resolve, reject) => {
        let buf = "";
        arguments.unshift(path)
        const python = spawn("python", arguments);
    
        python.stdout.on("data", (data) => {
          buf += data;
        });
    
        python.stderr.on("data", (data) => {
          console.error(`stderr: ${data}`);
        });
    
        python.on("close", (code) => {
          if (code !== 0) {
            return reject(`child process died with ${code}`);
          }
          const dataToSend = buf
          return resolve(dataToSend);
        });
      });
}



//in any other file
//first import the function

//how to use the function
(async () => {
  data = await pythonRunner("path/to/python/file", ["arg1", "arg2"])
  console.log(data)
})()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将json格式的数据返回到javascript ajax调用 - how to return data in json format to javascript ajax call 如何将以JSON格式返回的数据分组并返回? - How can I group data returned in JSON format and return it? 如何将表单数据传递到客户端函数(google.scripts.run)并将结果返回到HTML? - How to pass a form data to a client side function (google.scripts.run) and return result to HTML? 如何将Javascript连接到Python以两种方式共享JSON格式的数据? - How to connect Javascript to Python sharing data with JSON format in both ways? 如何通过单击页面运行 JavaScript 函数? - How can I run a JavaScript function with any click on the page? 如何运行函数并将输出作为图像 src javascript 返回 - How can I run a function and return output as image src javascript Firebug - 如何运行多行脚本或创建新的JavaScript文件? - Firebug - how can I run multiline scripts or create a new JavaScript file? 如何将数据从 JavaScript 传递到 python 脚本? - How to pass data to python scripts from JavaScript? 任何Javascript DateTime函数返回MySQL日期时间格式? - Any Javascript DateTime Function return MySQL datetime format? 没有脚本的情况下如何运行concat? - How can I run concat for cases without any scripts?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM