跨平台抽象层完整实现
import sys
import platform
import os
from typing import Dict, Any, Optional, Callable
from dataclasses import dataclass, field
from enum import Enum
from pathlib import Path
import subprocess
class PlatformType(Enum):
"""平台类型"""
WINDOWS = "windows"
MACOS = "macos"
LINUX = "linux"
ANDROID = "android"
IOS = "ios"
WEB = "web"
UNKNOWN = "unknown"
class ArchitectureType(Enum):
"""架构类型"""
X86 = "x86"
X86_64 = "x86_64"
ARM = "arm"
ARM64 = "arm64"
UNKNOWN = "unknown"
@dataclass
class PlatformInfo:
"""平台信息"""
platform_type: PlatformType
architecture: ArchitectureType
os_name: str
os_version: str
python_version: str
is_64bit: bool
processor: str
@classmethod
def detect(cls) -> 'PlatformInfo':
"""检测当前平台信息"""
system = platform.system().lower()
machine = platform.machine().lower()
# 检测平台类型
if system == "windows":
platform_type = PlatformType.WINDOWS
elif system == "darwin":
platform_type = PlatformType.MACOS
elif system == "linux":
# 检测是否为 Android
if os.path.exists("/system/bin"):
platform_type = PlatformType.ANDROID
else:
platform_type = PlatformType.LINUX
elif system == "java":
# 检测是否为 Android/iOS (通过 Jython)
platform_type = PlatformType.UNKNOWN
else:
platform_type = PlatformType.UNKNOWN
# 检测架构
if machine in ("x86", "i386", "i686"):
architecture = ArchitectureType.X86
elif machine in ("x86_64", "amd64", "x64"):
architecture = ArchitectureType.X86_64
elif machine in ("arm", "armv7l"):
architecture = ArchitectureType.ARM
elif machine in ("arm64", "aarch64"):
architecture = ArchitectureType.ARM64
else:
architecture = ArchitectureType.UNKNOWN
return cls(
platform_type=platform_type,
architecture=architecture,
os_name=system,
os_version=platform.version(),
python_version=platform.python_version(),
is_64bit=platform.architecture()[0] == "64bit",
processor=platform.processor()
)
def __str__(self) -> str:
return (f"{self.platform_type.value} ({self.architecture.value}) - "
f"{self.os_name} {self.os_version[:20]}")
@dataclass
class PlatformAdapter:
"""平台适配器"""
platform_info: PlatformInfo
adapters: Dict[str, Callable] = field(default_factory=dict)
def register_adapter(self, feature: str, adapter: Callable):
"""注册平台适配器"""
self.adapters[feature] = adapter
def get_adapter(self, feature: str) -> Optional[Callable]:
"""获取平台适配器"""
return self.adapters.get(feature)
def execute_platform_specific(self, feature: str, *args, **kwargs) -> Any:
"""执行平台特定操作"""
adapter = self.get_adapter(feature)
if adapter:
return adapter(*args, **kwargs)
else:
raise NotImplementedError(f"No adapter registered for feature: {feature}")
class CrossPlatformExecutor:
"""
跨平台执行器
核心功能:
1. 平台检测
2. 抽象层提供
3. 平台适配
4. 原生 API 桥接
5. 兼容性保障
"""
def __init__(self):
self.platform_info = PlatformInfo.detect()
self.adapter = PlatformAdapter(self.platform_info)
self._register_default_adapters()
def _register_default_adapters(self):
"""注册默认平台适配器"""
# 文件系统路径适配器
self.adapter.register_adapter("path_separator", self._get_path_separator)
self.adapter.register_adapter("home_dir", self._get_home_dir)
self.adapter.register_adapter("config_dir", self._get_config_dir)
# 系统命令适配器
self.adapter.register_adapter("open_file", self._open_file)
self.adapter.register_adapter("copy_to_clipboard", self._copy_to_clipboard)
# UI 适配器
self.adapter.register_adapter("system_font", self._get_system_font)
self.adapter.register_adapter("theme", self._get_system_theme)
def _get_path_separator(self) -> str:
"""获取路径分隔符"""
if self.platform_info.platform_type == PlatformType.WINDOWS:
return "\\"
else:
return "/"
def _get_home_dir(self) -> Path:
"""获取用户主目录"""
return Path.home()
def _get_config_dir(self) -> Path:
"""获取配置目录"""
if self.platform_info.platform_type == PlatformType.WINDOWS:
return Path(os.environ.get("APPDATA", ""))
elif self.platform_info.platform_type == PlatformType.MACOS:
return Path.home() / "Library" / "Application Support"
else: # Linux/Android
return Path.home() / ".config"
def _open_file(self, file_path: str):
"""打开文件"""
if self.platform_info.platform_type == PlatformType.WINDOWS:
os.startfile(file_path)
elif self.platform_info.platform_type == PlatformType.MACOS:
subprocess.run(["open", file_path])
else: # Linux/Android
subprocess.run(["xdg-open", file_path])
def _copy_to_clipboard(self, text: str):
"""复制到剪贴板"""
if self.platform_info.platform_type == PlatformType.WINDOWS:
subprocess.run(["clip"], input=text.encode())
elif self.platform_info.platform_type == PlatformType.MACOS:
subprocess.run(["pbcopy"], input=text.encode())
else: # Linux
try:
subprocess.run(["xclip", "-selection", "clipboard"], input=text.encode())
except FileNotFoundError:
subprocess.run(["xsel", "--clipboard", "--input"], input=text.encode())
def _get_system_font(self) -> str:
"""获取系统字体"""
if self.platform_info.platform_type == PlatformType.WINDOWS:
return "Segoe UI"
elif self.platform_info.platform_type == PlatformType.MACOS:
return "San Francisco"
else: # Linux
return "Ubuntu"
def _get_system_theme(self) -> str:
"""获取系统主题"""
# 简化实现,实际应检测系统主题设置
return "light"
def get_platform_info(self) -> Dict[str, Any]:
"""获取平台信息"""
return {
"platform": self.platform_info.platform_type.value,
"architecture": self.platform_info.architecture.value,
"os_name": self.platform_info.os_name,
"os_version": self.platform_info.os_version,
"python_version": self.platform_info.python_version,
"is_64bit": self.platform_info.is_64bit,
"processor": self.platform_info.processor
}
def is_platform(self, platform_type: PlatformType) -> bool:
"""检查是否为指定平台"""
return self.platform_info.platform_type == platform_type
def execute_cross_platform(self, operation: str, **kwargs) -> Any:
"""
执行跨平台操作
Args:
operation: 操作名称
**kwargs: 操作参数
Returns:
操作结果
"""
return self.adapter.execute_platform_specific(operation, **kwargs)
# 使用示例
if __name__ == "__main__":
# 创建跨平台执行器
executor = CrossPlatformExecutor()
print("=== 跨平台执行器 ===")
print(f"\n当前平台信息:")
platform_info = executor.get_platform_info()
for key, value in platform_info.items():
print(f" {key}: {value}")
print(f"\n平台类型:{executor.platform_info.platform_type.value}")
print(f"架构类型:{executor.platform_info.architecture.value}")
print(f"是否 64 位:{executor.platform_info.is_64bit}")
print("\n=== 跨平台操作示例 ===")
# 路径分隔符
separator = executor.execute_cross_platform("path_separator")
print(f"\n路径分隔符:{separator}")
# 主目录
home_dir = executor.execute_cross_platform("home_dir")
print(f"主目录:{home_dir}")
# 配置目录
config_dir = executor.execute_cross_platform("config_dir")
print(f"配置目录:{config_dir}")
# 系统字体
font = executor.execute_cross_platform("system_font")
print(f"系统字体:{font}")
# 系统主题
theme = executor.execute_cross_platform("theme")
print(f"系统主题:{theme}")
print("\n关键观察:")
print("1. 平台检测:自动检测操作系统、架构、版本")
print("2. 抽象层:提供统一的 API 接口,屏蔽平台差异")
print("3. 适配器:为不同平台注册特定实现")
print("4. 可扩展:支持注册自定义适配器")
print("5. 向后兼容:保证旧版本系统兼容性")
print("\n=== 跨平台优势 ===")
print("• 代码复用:一套代码多端运行")
print("• 成本降低:减少 70%+ 开发工作量")
print("• 体验一致:保证多平台用户体验一致性")
print("• 快速迭代:新功能同步上线所有平台")
print("• 生态扩展:快速覆盖更多平台和用户")