簡體   English   中英

如何創建一個通用的 JavaScript 函數,它可以運行 python 腳本並以 json 格式返回數據(如果有)?

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

我目前能夠做什么

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()
}



我想要達到的目標

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
}

基本上,我想創建一個函數,該函數可以帶或不帶參數運行任何給定的 python 文件並返回其輸出。
請注意:我想完成pythonFileRunner()函數中的所有async-await內容。 這個函數必須只返回輸出,我可以根據我的用例修改它

如果我采取了錯誤的方法,請在評論中告訴我。

應該是基本一樣的。 只需更換

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

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

我幾乎沒有修改 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM