[英]Execute Python script from Node.js and wait for termination
我正在使用 Node.js 构建一个 API-Rest,并且需要执行一个 python 脚本,该脚本将生成一个.json 文件并将其保存在一个目录中。 因此,我想等待 python 程序终止,以便节点可以使用 output JSON 文件。 这是我从如何从 Node.js 调用 Python function
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;
调用 function:
...
route: async function(req, res){
const pythonCaller = require("../models/routeGeneration");
const locaciones = require("../models/example");
const result = await pythonCaller.callPython("CVRP.py", {"delivery":locations});
}
...
认为这不起作用,因为我永远等待 state,有人可以帮助我吗? 谢谢
Promise { <pending> }
我同意@Molda。 我假设stdout.on("end")
在这种情况下适用于EOF
。 如果它完全发出。 process.stdout是net.Socket
所以Socket.on('end')是我找到的最接近的适用信息。 这确实暗示了我在net
环境中所做的相同假设。 我找不到更具体的东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.