首页 > web前端 > js教程 > 正文

使用 Node.js 子进程与 Python 脚本交互:解决数据传递问题

聖光之護
发布: 2025-09-11 17:52:01
原创
828人浏览过

使用 node.js 子进程与 python 脚本交互:解决数据传递问题

本文旨在解决在使用 Node.js 的 child_process.spawn 方法调用 Python 脚本,并在异步函数中处理数据时遇到的常见问题。我们将详细介绍如何正确地传递数据给 Python 脚本,并从 Python 脚本中获取结果,确保在 MERN 栈应用中顺利集成 Python 机器学习算法。主要内容包括文件路径问题、数据序列化与反序列化、以及异步函数中的正确使用方法。

理解 child_process.spawn

child_process.spawn 是 Node.js 中用于创建子进程的强大工具。它允许你执行外部命令,例如运行 Python 脚本,并与其进行数据交互。

问题分析:数据为空的原因

在异步函数(如 async 函数)中使用 child_process.spawn 时,常见的问题是接收到的数据为空。这通常由以下几个原因导致:

  1. 文件路径错误:Node.js 可能无法找到 Python 脚本。
  2. 数据序列化/反序列化问题:传递给 Python 脚本的数据格式不正确,或者从 Python 脚本返回的数据无法被 Node.js 正确解析。
  3. 异步操作处理不当:在异步函数中,数据可能在子进程完成之前就被处理,导致数据为空。

解决方案

以下是一个完整的解决方案,包括代码示例和详细解释。

立即学习Python免费学习笔记(深入)”;

1. 确保 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 可以确保跨平台兼容性。

2. 数据序列化与反序列化

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 (接收和发送数据):

AI建筑知识问答
AI建筑知识问答

用人工智能ChatGPT帮你解答所有建筑问题

AI建筑知识问答22
查看详情 AI建筑知识问答
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()
登录后复制

注意:

  • 在 Python 中,使用 sys.stdin.read() 读取所有输入数据。
  • 使用 json.dumps() 将 Python 对象序列化为 JSON 字符串。
  • 使用 sys.stdout.flush() 确保数据被立即发送到 Node.js。
  • 在 Node.js 中,使用 Buffer.concat(buffers).toString() 将缓冲区数据转换为字符串,然后使用 JSON.parse() 将其解析为 JavaScript 对象。

3. 错误处理

添加错误处理可以帮助你诊断问题。

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)
登录后复制

4. 异步函数中的正确使用

确保你在 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中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号