Magic Mirror模块开发:Node.js子进程无法获取Python循环脚本持续输出的问题咨询
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
exitanderrorevents are attached totask.stdoutinstead of thetaskobject itself. These events belong to the child process, not its stdout stream. - The
errorhandler uses an undefined variableerror(you named the parameterdata). self = thisis 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
- Apply either the
-uflag in Node.js or theflush=Truein Python. - Replace your existing
node_helper.jswith the corrected version above. - 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
sendSocketNotificationif needed.
内容的提问来源于stack exchange,提问作者Álex Blázquez Ruiz

