0

0

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

聖光之護

聖光之護

发布时间:2025-09-11 17:52:01

|

845人浏览过

|

来源于php中文网

原创

使用 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

谱乐AI,集成 Suno、Udio 等顶尖AI音乐模型的一站式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 脚本,并进行数据交互。 确保添加适当的错误处理,以便在出现问题时能够快速诊断和解决。

相关专题

更多
python开发工具
python开发工具

php中文网为大家提供各种python开发工具,好的开发工具,可帮助开发者攻克编程学习中的基础障碍,理解每一行源代码在程序执行时在计算机中的过程。php中文网还为大家带来python相关课程以及相关文章等内容,供大家免费下载使用。

751

2023.06.15

python打包成可执行文件
python打包成可执行文件

本专题为大家带来python打包成可执行文件相关的文章,大家可以免费的下载体验。

636

2023.07.20

python能做什么
python能做什么

python能做的有:可用于开发基于控制台的应用程序、多媒体部分开发、用于开发基于Web的应用程序、使用python处理数据、系统编程等等。本专题为大家提供python相关的各种文章、以及下载和课程。

758

2023.07.25

format在python中的用法
format在python中的用法

Python中的format是一种字符串格式化方法,用于将变量或值插入到字符串中的占位符位置。通过format方法,我们可以动态地构建字符串,使其包含不同值。php中文网给大家带来了相关的教程以及文章,欢迎大家前来阅读学习。

618

2023.07.31

python教程
python教程

Python已成为一门网红语言,即使是在非编程开发者当中,也掀起了一股学习的热潮。本专题为大家带来python教程的相关文章,大家可以免费体验学习。

1262

2023.08.03

python环境变量的配置
python环境变量的配置

Python是一种流行的编程语言,被广泛用于软件开发、数据分析和科学计算等领域。在安装Python之后,我们需要配置环境变量,以便在任何位置都能够访问Python的可执行文件。php中文网给大家带来了相关的教程以及文章,欢迎大家前来学习阅读。

547

2023.08.04

python eval
python eval

eval函数是Python中一个非常强大的函数,它可以将字符串作为Python代码进行执行,实现动态编程的效果。然而,由于其潜在的安全风险和性能问题,需要谨慎使用。php中文网给大家带来了相关的教程以及文章,欢迎大家前来学习阅读。

577

2023.08.04

scratch和python区别
scratch和python区别

scratch和python的区别:1、scratch是一种专为初学者设计的图形化编程语言,python是一种文本编程语言;2、scratch使用的是基于积木的编程语法,python采用更加传统的文本编程语法等等。本专题为大家提供scratch和python相关的文章、下载、课程内容,供大家免费下载体验。

706

2023.08.11

Java 桌面应用开发(JavaFX 实战)
Java 桌面应用开发(JavaFX 实战)

本专题系统讲解 Java 在桌面应用开发领域的实战应用,重点围绕 JavaFX 框架,涵盖界面布局、控件使用、事件处理、FXML、样式美化(CSS)、多线程与UI响应优化,以及桌面应用的打包与发布。通过完整示例项目,帮助学习者掌握 使用 Java 构建现代化、跨平台桌面应用程序的核心能力。

36

2026.01.14

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
React 教程
React 教程

共58课时 | 3.6万人学习

TypeScript 教程
TypeScript 教程

共19课时 | 2.2万人学习

Bootstrap 5教程
Bootstrap 5教程

共46课时 | 2.9万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

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