
本文旨在解决在使用 Node.js 的 child_process.spawn 方法调用 Python 脚本,并在异步函数中处理数据时遇到的常见问题。我们将详细介绍如何正确地传递数据给 Python 脚本,并从 Python 脚本中获取结果,确保在 MERN 栈应用中顺利集成 Python 机器学习算法。主要内容包括文件路径问题、数据序列化与反序列化、以及异步函数中的正确使用方法。
child_process.spawn 是 Node.js 中用于创建子进程的强大工具。它允许你执行外部命令,例如运行 Python 脚本,并与其进行数据交互。
在异步函数(如 async 函数)中使用 child_process.spawn 时,常见的问题是接收到的数据为空。这通常由以下几个原因导致:
以下是一个完整的解决方案,包括代码示例和详细解释。
立即学习“Python免费学习笔记(深入)”;
这是最常见的问题。确保 Node.js 能够找到你的 Python 脚本。建议使用绝对路径或相对于 Node.js 脚本的相对路径。
const { spawn } = require("child_process");
const path = require('path');
const pythonScriptPath = path.join(__dirname, '..', 'python', 'model.py'); // 假设 model.py 在上一级目录的 python 文件夹下
const python = spawn('python', [pythonScriptPath]);注意: 使用 path.join 可以确保跨平台兼容性。
Node.js 和 Python 之间的数据交换通常需要序列化和反序列化。JSON 是一种常用的格式。
Node.js (发送数据):
const createSchedule = async (req, res) => {
const { spawn } = require("child_process");
const path = require('path');
const pythonScriptPath = path.join(__dirname, '..', 'python', 'model.py'); // 假设 model.py 在上一级目录的 python 文件夹下
const python = spawn('python', [pythonScriptPath]);
const buffers = [];
python.stdout.on('data', (chunk) => buffers.push(chunk));
python.stdout.on('end', () => {
console.log(buffers)
if (buffers.length > 0) {
try {
const result = JSON.parse(Buffer.concat(buffers).toString());
console.log('Python process exited, result:', result);
res.status(200).json(result);
} catch (error) {
console.error("Error parsing JSON:", error);
res.status(500).json({ error: "Failed to parse Python output" });
}
} else {
console.log('Python process exited with no output');
res.status(400).json({ error: "Python script returned no output" })
}
});
python.stderr.on('data', (data) => {
console.error(`Python script error: ${data}`);
});
let num_tas = 5
let num_days = 6
let num_slots = 5
let num_courses = 3
let num_tutorialGroups = 5
// 5
let taCourseAssignment = [
[9, 6, 0],
[3, 6, 0],
[3, 0, 12],
[9, 0, 0],
[6, 0, 6]
]
console.log(taCourseAssignment)
// 6
let taDayOffPreference = [
[6, 5, 3, 4, 2, 1],
[1, 2, 6, 5, 4, 3],
[1, 2, 3, 4, 5, 6],
[1, 2, 3, 6, 4, 5],
[6, 1, 5, 4, 3, 2],
]
// 7
let sessionNumberPreference = [
[2, 2, 2, 2, 2, 2],
[2, 2, 2, 2, 2, 2],
[0, 2, 2, 2, 2, 2],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
]
// 8
let schedule = [
// sat
[[[1, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]],
[[1, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]],
[[0, 1, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]],
[[1, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]],
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
],
// sun
[[[0, 0, 0, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1]],
[[0, 0, 0, 1, 1], [0, 0, 1, 0, 0], [0, 1, 0, 0, 0]],
[[0, 1, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]],
[[0, 0, 1, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 1]],
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
],
// mon
[[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]],
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]],
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]],
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]],
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
],
// tue
[[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]],
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]],
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]],
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]],
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
],
// wed
[[[0, 0, 0, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1]],
[[0, 0, 0, 1, 1], [0, 0, 1, 0, 0], [0, 1, 0, 0, 0]],
[[0, 1, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]],
[[0, 0, 1, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 1]],
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
],
// thu
[[[0, 0, 0, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1]],
[[0, 0, 0, 1, 1], [0, 0, 1, 0, 0], [0, 1, 0, 0, 0]],
[[0, 1, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]],
[[0, 0, 1, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 1]],
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
],
]
python.stdin.write(JSON.stringify([num_tas, num_days, num_slots, num_courses, num_tutorialGroups, taCourseAssignment, taDayOffPreference, sessionNumberPreference, schedule]));
python.stdin.end()
}Python (接收和发送数据):
import sys
import json
# 读取 Node.js 传递的数据
data = json.loads(sys.stdin.read())
num_tas, num_days, num_slots, num_courses, num_tutorialGroups, taCourseAssignment, taDayOffPreference, sessionNumberPreference, schedule = data
# 在这里执行你的机器学习算法
result = {"message": "Hello from Python!", "data": data} # 示例结果
# 将结果序列化为 JSON 并发送回 Node.js
print(json.dumps(result))
sys.stdout.flush()注意:
添加错误处理可以帮助你诊断问题。
Node.js:
python.stderr.on('data', (data) => {
console.error(`Python script error: ${data}`);
});Python:
import traceback
import sys
try:
# 你的代码
pass
except Exception as e:
traceback.print_exc()
sys.exit(1)确保你在 stdout.on('end', ...) 中处理数据,因为这是 Python 脚本执行完毕并返回数据的时间点。
Node.js:
const { spawn } = require("child_process");
const path = require('path');
const createSchedule = async (req, res) => {
const pythonScriptPath = path.join(__dirname, '..', 'python', 'model.py');
const python = spawn('python', [pythonScriptPath]);
const buffers = [];
python.stdout.on('data', (chunk) => buffers.push(chunk));
python.stdout.on('end', () => {
if (buffers.length > 0) {
try {
const result = JSON.parse(Buffer.concat(buffers).toString());
console.log('Python process exited, result:', result);
res.status(200).json(result);
} catch (error) {
console.error("Error parsing JSON:", error);
res.status(500).json({ error: "Failed to parse Python output" });
}
} else {
console.log('Python process exited with no output');
res.status(400).json({ error: "Python script returned no output" });
}
});
python.stderr.on('data', (data) => {
console.error(`Python script error: ${data}`);
});
// 示例数据
const dataToSend = { message: "Hello from Node.js!" };
python.stdin.write(JSON.stringify(dataToSend));
python.stdin.end();
};Python:
import sys
import json
try:
data = json.loads(sys.stdin.read())
print(json.dumps({"message": "Hello from Python!", "received": data}))
sys.stdout.flush()
except Exception as e:
import traceback
traceback.print_exc()
sys.exit(1)通过正确处理文件路径、数据序列化/反序列化以及异步操作,你可以成功地在 Node.js 应用中使用 child_process.spawn 调用 Python 脚本,并进行数据交互。 确保添加适当的错误处理,以便在出现问题时能够快速诊断和解决。
以上就是使用 Node.js 子进程与 Python 脚本交互:解决数据传递问题的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号