Files
personal-experiment/shutdown_handler.py
2026-03-06 17:07:57 +08:00

195 lines
5.2 KiB
Python

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
关机处理模块
提供不同操作系统的关机实现
"""
import os
import sys
import platform
from abc import ABC, abstractmethod
from typing import Optional
class ShutdownHandler(ABC):
"""关机处理器抽象基类(策略模式)"""
def __init__(self, delay: int = 5, message: str = "系统即将关机"):
"""
初始化关机处理器
Args:
delay: 延迟关机时间(秒)
message: 关机提示信息
"""
self.delay = delay
self.message = message
@abstractmethod
def execute(self) -> bool:
"""
执行关机操作
Returns:
是否成功执行关机命令
"""
pass
@abstractmethod
def get_command(self) -> str:
"""
获取关机命令
Returns:
关机命令字符串
"""
pass
def log_shutdown(self, reason: str) -> None:
"""
记录关机信息
Args:
reason: 关机原因
"""
print(f"\n{'='*60}")
print(f"系统关机")
print(f"{'='*60}")
print(f"原因: {reason}")
print(f"延迟: {self.delay} 秒")
print(f"{'='*60}\n")
class WindowsShutdownHandler(ShutdownHandler):
"""Windows关机处理器"""
def execute(self) -> bool:
"""执行Windows关机"""
try:
command = self.get_command()
os.system(command)
return True
except Exception as e:
print(f"执行关机命令失败: {e}")
return False
def get_command(self) -> str:
"""获取Windows关机命令"""
# 将消息中的双引号转义
escaped_message = self.message.replace('"', '""')
return f'shutdown /s /t {self.delay} /c "{escaped_message}"'
class LinuxShutdownHandler(ShutdownHandler):
"""Linux关机处理器"""
def execute(self) -> bool:
"""执行Linux关机"""
try:
command = self.get_command()
os.system(command)
return True
except Exception as e:
print(f"执行关机命令失败: {e}")
return False
def get_command(self) -> str:
"""获取Linux关机命令"""
# Linux关机延迟通常以分钟为单位
delay_minutes = max(1, self.delay // 60)
return f'shutdown -h +{delay_minutes} "{self.message}"'
class MacOSShutdownHandler(ShutdownHandler):
"""macOS关机处理器"""
def execute(self) -> bool:
"""执行macOS关机"""
try:
command = self.get_command()
os.system(command)
return True
except Exception as e:
print(f"执行关机命令失败: {e}")
return False
def get_command(self) -> str:
"""获取macOS关机命令"""
# macOS关机延迟通常以分钟为单位
delay_minutes = max(1, self.delay // 60)
return f'shutdown -h +{delay_minutes} "{self.message}"'
class DummyShutdownHandler(ShutdownHandler):
"""模拟关机处理器(用于测试)"""
def execute(self) -> bool:
"""执行模拟关机(仅打印消息)"""
print(f"[模拟关机] 系统将在 {self.delay} 秒后关机")
print(f"[模拟关机] 原因: {self.message}")
return True
def get_command(self) -> str:
"""返回模拟命令"""
return "echo '模拟关机'"
class ShutdownHandlerFactory:
"""关机处理器工厂类(工厂模式)"""
_handlers: dict = {
'windows': WindowsShutdownHandler,
'linux': LinuxShutdownHandler,
'darwin': MacOSShutdownHandler
}
@classmethod
def create(cls, delay: int = 5, message: str = "系统即将关机") -> ShutdownHandler:
"""
根据当前操作系统创建关机处理器
Args:
delay: 延迟关机时间(秒)
message: 关机提示信息
Returns:
适配当前系统的关机处理器实例
Raises:
RuntimeError: 不支持的操作系统
"""
os_name = platform.system().lower()
handler_class = cls._handlers.get(os_name)
if handler_class is None:
raise RuntimeError(f"不支持的操作系统: {os_name}")
return handler_class(delay, message)
@classmethod
def create_dummy(cls, delay: int = 0, message: str = "模拟关机") -> ShutdownHandler:
"""
创建模拟关机处理器
Args:
delay: 延迟关机时间(秒)
message: 关机提示信息
Returns:
模拟关机处理器实例
"""
return DummyShutdownHandler(delay, message)
@classmethod
def register_handler(cls, os_name: str, handler_class: type) -> None:
"""
注册自定义关机处理器
Args:
os_name: 操作系统名称
handler_class: 处理器类
"""
cls._handlers[os_name] = handler_class