
本文档旨在指导开发者如何在Node.js的异步请求处理函数中,通过child_process.spawn调用Python子进程,并有效地传递数据和接收结果。我们将重点讲解如何避免常见的文件路径问题,并提供示例代码,确保数据在Node.js和Python之间正确传输。
在构建 MERN (MongoDB, Express.js, React, Node.js) 应用程序时,有时需要在后端调用 Python 脚本来执行特定的任务,例如运行机器学习算法。Node.js 的 child_process 模块提供了 spawn 函数,允许我们创建子进程来执行这些外部脚本。
以下是一个在 Node.js 的 Express 路由中,使用 child_process.spawn 调用 Python 脚本的示例:
const express = require('express');
const { spawn } = require("child_process");
const app = express();
const port = 3000;
app.use(express.json()); // Middleware to parse JSON bodies
app.post('/run-python', async (req, res) => {
try {
const { data } = req.body; // Receive data from the request body
const pythonProcess = spawn('python', ['path/to/your/model.py']); // Replace with the actual path to your Python script
const buffers = [];
// Collect data from stdout
pythonProcess.stdout.on('data', (chunk) => {
buffers.push(chunk);
});
// Handle errors from stderr
pythonProcess.stderr.on('data', (data) => {
console.error(`stderr: ${data}`);
return res.status(500).json({ error: `Python script error: ${data}` });
});
pythonProcess.on('close', (code) => {
if (code === 0) {
try {
const result = JSON.parse(Buffer.concat(buffers).toString());
console.log('Python process exited with result:', result);
res.status(200).json(result);
} catch (error) {
console.error('Error parsing JSON:', error);
res.status(500).json({ error: 'Error parsing JSON from Python script' });
}
} else {
console.error(`Python process exited with code ${code}`);
res.status(500).json({ error: `Python script exited with code ${code}` });
}
});
// Send data to the Python script via stdin
pythonProcess.stdin.write(JSON.stringify(data));
pythonProcess.stdin.end();
} catch (error) {
console.error('Error running python script:', error);
res.status(500).json({ error: 'Failed to execute python script' });
}
});
app.listen(port, () => {
console.log(`Example app listening on port ${port}`);
});Python 脚本 (model.py) 示例:
立即学习“Python免费学习笔记(深入)”;
import json
import sys
# Read data from stdin
data = json.loads(sys.stdin.read())
# Process the data
result = {"message": "Data received and processed successfully!", "input": data}
# Return the result as JSON to stdout
print(json.dumps(result))
sys.stdout.flush()通过 child_process.spawn,我们可以方便地在 Node.js 应用程序中调用 Python 脚本,实现更复杂的功能。关键在于正确处理文件路径、数据格式和错误信息。遵循本文档中的示例和注意事项,可以帮助你避免常见问题,并成功地将 Python 集成到你的 MERN 应用程序中。
以上就是在Node.js异步请求中调用Python子进程并处理数据的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号