从Node.js执行Python脚本并等待终止



我正在用Node.js构建一个API-Rest,需要执行一个python脚本,该脚本将生成一个.json文件并将其保存在一个目录中。因此,我想等待python程序的终止,以便节点可以使用输出的JSON文件。这是我从中实现的代码如何从Node.js 调用Python函数

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

我同意@Molda的观点。在这种情况下,我假设stdout.on("end")是针对EOF的。如果它是发射的。process.stdout是一个net.Socket,所以Socket.on('end'(是我找到的最接近的适用信息。这确实意味着我在net上下文中做出的相同假设。我找不到更具体的了。

最新更新