一.简介
通过在pypi上的搜索,我发现了几个有趣的库,在详细"学习"后,写了如下代码
二、代码
python
import psutil
import os
import time
import ctypes
import threadingdef 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_SYSTEMMODALdef 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()
三.结语
如果喜欢就点个赞鼓励一下😃