You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Magic Mirror模块开发:Node.js子进程无法获取Python循环脚本持续输出的问题咨询

Fixing Magic Mirror Module: Capturing Output from a Long-Running Python Loop

Hey there! I get it—working with child processes and long-running scripts can be tricky, especially when output doesn’t show up like you expect. Let’s break down why your Python loop’s output isn’t reaching your Node.js helper, and fix it step by step.

The Root Cause: Python’s Output Buffering

When Python runs in a non-interactive environment (like being spawned by Node.js), its standard output (stdout) uses block buffering by default. That means it holds onto output until the buffer is full (usually 4KB or so) before sending it to the parent process. In your While True loop, if you’re printing small chunks of text, they’ll sit in the buffer forever instead of being sent to Node.js immediately—hence why you see nothing in the logs or Magic Mirror interface.

Solutions to Unlock the Output

You have two straightforward ways to fix this:

1. Force Python to Disable Buffering

Add the -u flag when spawning the Python process. This tells Python to use unbuffered stdout/stderr, so every print statement sends output right away:

const task = spawn('python3', ['-u', '/Fotos/reconeixementfacial.py'])

2. Flush Output in Your Python Script

If you prefer to modify the Python code instead, add flush=True to every print() call to manually push the output out of the buffer:

while True:
    # Your existing logic here
    print("Your output text", flush=True)
    # Rest of your loop code

Fixing Issues in Your node_helper.js

Beyond the buffering problem, there are a few small bugs in your Node.js code that might be causing headaches:

  • The exit and error events are attached to task.stdout instead of the task object itself. These events belong to the child process, not its stdout stream.
  • The error handler uses an undefined variable error (you named the parameter data).
  • self = this is declared outside the module scope, so it doesn’t reference the NodeHelper instance correctly.
  • Using task.unref() might cause the child process to be terminated unexpectedly if Node.js thinks there’s no active reference to it.

Here’s the corrected node_helper.js code:

var NodeHelper = require("node_helper")
var { spawn } = require("child_process")

module.exports = NodeHelper.create({
    start: function() {
        this.startPythonTask();
    },

    startPythonTask: function() {
        const self = this;
        const task = spawn('python3', ['-u', '/Fotos/reconeixementfacial.py']);

        task.stdout.on('data', (data) => {
            console.log(`Python output: ${data}`);
            // If you need to send this to the Magic Mirror frontend, use:
            // self.sendSocketNotification('PYTHON_OUTPUT', data.toString().trim());
        });

        task.on('exit', (code) => {
            console.log(`Python process exited with code: ${code}`);
            // Optional: Restart the task if it exits unexpectedly
            // setTimeout(() => self.startPythonTask(), 1000);
        });

        task.on('error', (error) => {
            console.error(`Failed to start Python process: ${error.message}`);
        });

        // Store the task reference to prevent garbage collection
        this.pythonTask = task;
    },

    socketNotificationReceived: function(notification, payload) {
        console.log(`Received notification: ${notification}`);
    }
})

Testing the Fix

  1. Apply either the -u flag in Node.js or the flush=True in Python.
  2. Replace your existing node_helper.js with the corrected version above.
  3. Restart your Magic Mirror module—you should now see the Python loop’s output in the console, and you can send it to the frontend using sendSocketNotification if needed.

内容的提问来源于stack exchange,提问作者Álex Blázquez Ruiz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 14:47:49