添加系统、版本检测以及依赖安装

This commit is contained in:
wzy-warehouse
2026-05-08 16:16:48 +08:00
parent 4ef23fec7c
commit c1fb472c4a
6 changed files with 223 additions and 38 deletions
+11
View File
@@ -1,3 +1,14 @@
""" """
Core functionality package Core functionality package
""" """
from app.core.env_checker import check_environment
from app.core.venv_manager import check_virtualenv
from app.core.dependency_manager import check_dependencies
from app.core.launcher import AppLauncher
__all__ = [
'check_environment',
'check_virtualenv',
'check_dependencies',
'AppLauncher',
]
+71
View File
@@ -0,0 +1,71 @@
"""
依赖管理模块
负责检查和管理项目依赖
"""
import sys
import json
import subprocess
from pathlib import Path
def check_dependencies(project_root: Path):
"""
检查并安装项目依赖
Args:
project_root: 项目根目录路径
"""
print("\n" + "=" * 50)
print("步骤 3: 依赖检查")
print("=" * 50)
requirements_file = project_root / "requirements.txt"
if not requirements_file.exists():
print(f"警告: 未找到 {requirements_file}")
return
try:
# 使用 pip list 检查已安装的包
result = subprocess.run(
[sys.executable, "-m", "pip", "list", "--format=json"],
capture_output=True,
text=True,
check=True
)
installed_packages = {pkg['name'].lower() for pkg in json.loads(result.stdout)}
# 读取 requirements.txt
with open(requirements_file, 'r', encoding='utf-8') as f:
required_packages = []
for line in f:
line = line.strip()
if line and not line.startswith('#'):
# 提取包名(去掉版本信息)
pkg_name = line.split('==')[0].split('>=')[0].split('<=')[0].strip()
if pkg_name:
required_packages.append((pkg_name.lower(), line))
# 检查缺失的依赖
missing_packages = [
req_line for pkg_name, req_line in required_packages
if pkg_name not in installed_packages
]
if missing_packages:
print(f"发现 {len(missing_packages)} 个未安装的依赖,正在安装...")
subprocess.run(
[sys.executable, "-m", "pip", "install", "-r", str(requirements_file)],
check=True
)
print("✓ 依赖安装完成")
else:
print("✓ 所有依赖已安装")
except subprocess.CalledProcessError as e:
print(f"✗ 依赖检查/安装失败: {e}")
sys.exit(1)
except Exception as e:
print(f"✗ 依赖检查出错: {e}")
sys.exit(1)
+40
View File
@@ -0,0 +1,40 @@
"""
环境检查模块
负责检查操作系统和Python版本
"""
import platform
def check_environment():
"""
检查系统和Python版本
Returns:
bool: 如果环境符合要求返回True,否则返回False
"""
print("\n" + "=" * 50)
print("步骤 1: 环境检查")
print("=" * 50)
# 识别操作系统
os_name = platform.system()
if os_name not in ['Windows', 'Linux']:
print(f"警告: 未测试的操作系统 {os_name},可能存在问题")
# 检查Python版本
python_version = platform.python_version()
# 解析版本号
major, minor, *_ = map(int, python_version.split('.'))
if major == 3 and minor == 13:
return True
else:
print(f"✗ Python版本不符合要求!")
print(f" 当前版本: {python_version}")
print(f" 要求版本: 3.13.x")
print(f"\n请使用 Python 3.13 版本运行此项目")
print(f"下载地址: https://www.python.org/downloads/")
return False
+53
View File
@@ -0,0 +1,53 @@
"""
应用启动器
"""
import sys
from pathlib import Path
from app.core.env_checker import check_environment
from app.core.venv_manager import check_virtualenv
from app.core.dependency_manager import check_dependencies
from app.utils.logger import get_logger
class AppLauncher:
"""应用启动器"""
def __init__(self, project_root: Path):
"""
初始化启动器
Args:
project_root: 项目根目录路径
"""
self.project_root = project_root
self.logger = get_logger()
def run(self):
"""执行完整的启动流程"""
try:
# 检查系统和Python版本
if not check_environment():
sys.exit(1)
# 检查虚拟环境
check_virtualenv(self.project_root)
# 检查安装依赖
check_dependencies(self.project_root)
# 启动应用
print("\n" + "=" * 50)
print("✓ 所有检查通过,准备启动应用...")
print("=" * 50)
self.logger.info("系统环境检查通过,开始执行主程序...")
self.start()
except Exception as e:
self.logger.error(f"启动失败: {e}")
sys.exit(1)
def start(self):
"""启动应用"""
self.logger.info("启动应用...")
print("启动成功!")
+44
View File
@@ -0,0 +1,44 @@
"""
虚拟环境管理模块
"""
import sys
import platform
import subprocess
from pathlib import Path
def check_virtualenv(project_root: Path) -> bool:
"""
检查并创建虚拟环境
Args:
project_root: 项目根目录路径
Returns:
bool: 如果虚拟环境已存在返回True,新创建则返回False
"""
print("\n" + "=" * 50)
print("步骤 2: 虚拟环境检查")
print("=" * 50)
venv_path = project_root / ".venv"
os_name = platform.system()
# 根据系统确定Python可执行文件路径
if os_name == 'Windows':
python_exe = venv_path / "Scripts" / "python.exe"
else: # Linux
python_exe = venv_path / "bin" / "python3"
if not venv_path.exists():
print(f"\n⚠ 虚拟环境不存在,正在创建...")
try:
subprocess.run([sys.executable, "-m", "venv", str(venv_path)], check=True)
print("✓ 虚拟环境创建成功")
return True # 继续执行后续步骤
except subprocess.CalledProcessError as e:
print(f"✗ 虚拟环境创建失败: {e}")
sys.exit(1)
else:
print(f"✓ 虚拟环境已存在: {venv_path}")
return True
+4 -38
View File
@@ -2,48 +2,14 @@
项目启动脚本 - 支持多环境和跨平台 项目启动脚本 - 支持多环境和跨平台
使用 Dynaconf 进行环境隔离配置 使用 Dynaconf 进行环境隔离配置
""" """
import sys
import platform
from pathlib import Path from pathlib import Path
from app.utils.logger import get_logger from app.core.launcher import AppLauncher
# 添加项目根目录到Python路径 # 添加项目根目录到Python路径
project_root = Path(__file__).parent project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))
logger = get_logger()
def check_environment():
"""检查系统和Python版本"""
# 识别操作系统
os_name = platform.system()
print(f"当前操作系统: {os_name}")
if os_name not in ['Windows', 'Linux']:
print(f"警告: 未测试的操作系统 {os_name},可能存在问题")
# 检查Python版本
python_version = platform.python_version()
print(f"当前Python版本: {python_version}")
# 解析版本号
major, minor, *_ = map(int, python_version.split('.'))
if major == 3 and minor == 13:
print("✓ Python版本符合要求 (3.13)")
return True
else:
print(f"✗ Python版本不符合要求!")
print(f" 当前版本: {python_version}")
print(f" 要求版本: 3.13.x")
print(f"\n请使用 Python 3.13 版本运行此项目")
print(f"下载地址: https://www.python.org/downloads/")
return False
def main():
check_environment()
if __name__ == "__main__": if __name__ == "__main__":
main() # 创建并运行启动器
launcher = AppLauncher(project_root)
launcher.run()