windows关闭应用并休眠电脑python代码

一.简介

通过在pypi上的搜索,我发现了几个有趣的库,在详细"学习"后,写了如下代码


二、代码

python

import psutil
import os
import time
import ctypes
import threading

def close_user_applications():
    # 用于存储需要弹窗的进程信息
    processes_to_notify = []

    # 遍历所有进程
    for proc in psutil.process_iter(['pid', 'name', 'username']):
        try:
            # 跳过系统进程和关键进程
            if proc.info['username'] is None or proc.info['username'].startswith('SYSTEM') or proc.info['username'].startswith('NT AUTHORITY'):
                continue
            
            # 跳过关键的用户进程
            if proc.info['name'] in ["python.exe", "cmd.exe", "explorer.exe", "taskmgr.exe"]:
                continue
            
            # 关闭进程
            proc.kill()
            print(f"Closed process: {proc.info['name']} (PID: {proc.info['pid']})")
            
            # 记录需要弹窗的进程信息
            processes_to_notify.append((proc.info['name'], proc.info['pid']))
        except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess) as e:
            print(f"Failed to close process {proc.info['pid']}: {e}")
    
    # 等待所有进程关闭
    time.sleep(5)
    
    # 一次性弹出所有弹窗
    threads = []
    for process_name, process_pid in processes_to_notify:
        thread = threading.Thread(target=show_message_box, args=(f"已关闭程序: {process_name} (PID: {process_pid})",))
        thread.start()
        threads.append(thread)
    
    # 等待所有弹窗线程完成
    for thread in threads:
        thread.join()

def show_message_box(message):
    """显示消息框"""
    ctypes.windll.user32.MessageBoxW(0, message, "通知", 0x40000)  # MB_SYSTEMMODAL

def put_computer_to_sleep():
    try:
        # 使用Windows API使电脑休眠
        ctypes.windll.powrprof.SetSuspendState(0, 1, 0)
        print("电脑即将休眠...")
    except Exception as e:
        print(f"休眠失败: {e}")

if __name__ == "__main__":
    for i in range(20):
        print(i)
        time.sleep(1)
    print("正在关闭所有用户应用程序...")
    close_user_applications()
    time.sleep(5)  # 等待几秒钟确保所有进程都已关闭
    
    print("电脑即将休眠...")
    put_computer_to_sleep()
 

三.结语

如果喜欢就点个赞鼓励一下😃

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值