Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

242
Visualizações
¿Cómo crear una función de JavaScript generalizada que pueda ejecutar scripts de Python y devolver datos en formato json, si corresponde?

Lo que soy capaz de hacer actualmente

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



lo que quiero lograr

 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 }

Básicamente, quiero crear una función que pueda ejecutar cualquier archivo de Python con o sin argumentos y devolver su salida.
Tenga en cuenta: quiero terminar todas las cosas async-await dentro de la función pythonFileRunner() . Esta función debe devolver solo la salida, que puedo modificar según mi caso de uso

Si estoy tomando el enfoque equivocado, házmelo saber en los comentarios.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Debe ser básicamente lo mismo. solo reemplaza

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

con

 const python = spawn("python", [ pathToFile, ...arguments ]);
about 4 years ago · Juan Pablo Isaza Relatório

0

He modificado un poco la función fetchweatherdata para obtener lo que quería.

 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) })()
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda