【发布时间】:2021-03-08 03:02:12
【问题描述】:
我正在使用 Node.js 构建一个 API-Rest,需要执行一个 python 脚本,该脚本将生成一个 .json 文件并将其保存在一个目录中。因此,我想等待 python 程序终止,以便节点可以使用输出 JSON 文件。这是我实现的代码 How to call a Python function from Node.js
const { spawn } = require('child_process');
const pythonDir = (__dirname + "./"); // Path of python script folder
const python = pythonDir + "./env/Scripts/python"; // Path of the Python interpreter
function cleanWarning(error) {
return error.replace(/Detector is not able to detect the language reliably.\n/g,"");
}
function callPython(scriptName, args) {
return new Promise(function(success, reject) {
const script = pythonDir + scriptName;
const pyArgs = [script, JSON.stringify(args) ]
const pyprog = spawn(python, pyArgs );
let resultError = "";
pyprog.stderr.on('data', (data) => {
resultError += cleanWarning(data.toString());
});
pyprog.stdout.on("end", function(){
if(resultError == "") {
var result = require('./optimalRoute.json')
success(result);
}else{
console.error(`Python error, you can reproduce the error with: \n${python} ${script} ${pyArgs.join(" ")}`);
const error = new Error(resultError);
console.error(error);
reject(resultError);
}
})
});
}
module.exports.callPython = callPython;
调用函数:
...
route: async function(req, res){
const pythonCaller = require("../models/routeGeneration");
const locaciones = require("../models/example");
const result = await pythonCaller.callPython("CVRP.py", {"delivery":locations});
}
...
认为这不起作用,因为我永远处于待处理状态,有人可以帮助我吗?谢谢
Promise { <pending> }
【问题讨论】:
-
你试过
pyprog.on('close',...)或pyprog.on('exit',...)吗?这里的文档nodejs.org/api/…
标签: javascript python node.js promise