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

如何使用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:

关闭树莓派智能魔镜程序与系统的Python方案

一、关闭智能魔镜程序

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 psutil library if you haven't already:

    pip install psutil
    
  • Python 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 skip psutil and 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:
    Run sudo visudo and add this line (replace pi with your username):
    pi ALL=(ALL) NOPASSWD: /sbin/shutdown
    
  • For testing, use sudo shutdown -h +1 instead of now — this gives you 1 minute to cancel with sudo shutdown -c if something goes wrong.

内容的提问来源于stack exchange,提问作者Smith john

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:26:55