如何使用Python关闭树莓派(含RPI3)上的程序?
Hey there! Let's walk through how to shut down your Magic Mirror app and even your Raspberry Pi (works for RPi 3 and most other models) using Python. Here's what you need to know:
一、关闭智能魔镜程序
Since Magic Mirror typically runs as a Node.js process, we can use the psutil library to locate and terminate it cleanly.
First, install the
psutillibrary if you haven't already:pip install psutilPython code to stop Magic Mirror:
This script scans running processes, identifies the Magic Mirror Node.js instance, and tries to shut it down gracefully (with a fallback to force termination if needed):import psutil def stop_magic_mirror(): # Loop through all active processes for proc in psutil.process_iter(['pid', 'name', 'cmdline']): try: # Check if it's a Node.js process tied to Magic Mirror # Adjust the 'MagicMirror' check to match your actual installation path if needed if proc.name() == 'node' and any('MagicMirror' in part for part in proc.cmdline()): print(f"Found Magic Mirror process (PID: {proc.pid}) — shutting down...") proc.terminate() # Try graceful shutdown first # Wait a few seconds to confirm termination; force kill if stuck try: proc.wait(timeout=3) print("Magic Mirror closed successfully!") except psutil.TimeoutExpired: proc.kill() print("Force-closed Magic Mirror successfully.") return except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess): continue print("No Magic Mirror process found running.") # Call the function to shut down the app stop_magic_mirror()If you use PM2 to manage Magic Mirror:
You can skippsutiland call PM2 directly from Python:import subprocess def stop_magic_mirror_pm2(): try: # Replace 'magicmirror' with your actual PM2 process name subprocess.run(['pm2', 'stop', 'magicmirror'], check=True) print("PM2-managed Magic Mirror has been shut down.") except subprocess.CalledProcessError: print("Failed to stop Magic Mirror via PM2 — check your process name or PM2 status.") stop_magic_mirror_pm2()
二、关闭树莓派系统
Once your Magic Mirror app is closed, you can also trigger a system shutdown directly from Python.
- Python code to shut down the Pi:
import subprocess def shutdown_rpi(): print("Shutting down Raspberry Pi...") try: # Execute the system shutdown command (requires sudo privileges) subprocess.run(['sudo', 'shutdown', '-h', 'now'], check=True) except subprocess.CalledProcessError: print("Shutdown failed — check if your script has sudo access.") # Combine app shutdown and system shutdown (optional) stop_magic_mirror() shutdown_rpi()
Important Notes:
- To avoid entering a sudo password every time, edit the sudoers file:
Runsudo visudoand add this line (replacepiwith your username):pi ALL=(ALL) NOPASSWD: /sbin/shutdown - For testing, use
sudo shutdown -h +1instead ofnow— this gives you 1 minute to cancel withsudo shutdown -cif something goes wrong.
内容的提问来源于stack exchange,提问作者Smith john

