javascript - 如何创建一个通用的 JavaScript 函数,该函数可以运行 python 脚本并以 json 格式返回数据(如果有)?
问题描述
我目前能做的
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 文件并返回其输出。
请注意:我想完成函数async-await
内的所有内容。pythonFileRunner()
这个函数必须只返回输出,我可以根据我的用例修改
如果我采取了错误的方法,请在评论中告诉我。
解决方案
应该基本一样。只需更换
const python = spawn("python", [
__dirname + "/weathergetter.py",
location.toString(),
]);
和
const python = spawn("python", [
pathToFile,
...arguments
]);
推荐阅读
- c# - 从托盘恢复应用程序
- ios - 故事板刷新问题Xcode
- django - 使用 django 通道的进程间通信在一小时后失败
- swift - Swift 4 的简单分页功能
- angular - (未知 url)的 Http 失败响应 - Docker 上的 Angular Universal(SSL)
- react-native - 为什么我收到 gulp-changed 错误?
- java - HTML 部署中的 LibGDX GwtApplication 异常 (TypeError)
- python - Python:将参数传递给函数
- ruby-on-rails - edit_password_reset_url(some_id_here) 如何解析为 https://example.com/password_resets/some_id_here/edit?
- plugins - 如何从某些环境中排除 babel 插件?