Node.js 路由器调用 Python 脚本绘制厂站图
This is a code snippet written in JavaScript using the Node.js framework. It defines a router that listens for a GET request with a parameter ID, and then spawns a child process to run a Python script with the given ID as an argument.
The Python script is located in a specific directory and is run with the 'python' command using the spawn method. The script's output is captured and logged to the console.
If the Python script exits successfully with a code of 0, the router renders a successful response. If the code is 255, it indicates that the requested data is not available and an appropriate error message is rendered. Finally, if the code is 1, it indicates a failure in the script execution and an error message is rendered.
const spawn = require('child_process').spawn;
router.get('/:id', (req, res, next) => {
const scriptPath = path.join(__dirname, '../public/pythonscripts/electric_substation_drawer/venv/main.py');
console.log(scriptPath);
console.log(req.params.id);
const pythonProcess = spawn('python', [scriptPath, req.params.id]);
pythonProcess.stdout.on('data', (pythonresult) => {
console.log(pythonresult.toString());
});
// pythonProcess.stderr.on('data', (data) => {
// console.log('*************' + data.toString());
// res.render('error', { message: 'python process Error', error: { status: 500, stack: data } });
// });
pythonProcess.on('exit', function (code, signal) {
console.log('python进程已退出,代码:' + code);
if (code == 0) {
try {
console.log('绘制成功');
res.render('substation');
} catch (error) {
console.error(error);
res.render('error', { message: 'Error', error: { status: 500, stack: data } });
}
}
if (code == 255) {
console.log('没有厂站图');
res.render('error', { message: '该厂站没有厂站图', error: { status: '', stack: '' } });
}
if (code == 1) {
console.log('绘制失败');
res.render('error', { message: '厂站图绘制失败', error: { status: '', stack: '' } });
}
});
});
原文地址: https://www.cveoy.top/t/topic/mOpn 著作权归作者所有。请勿转载和采集!