#!/usr/bin/env python """ Python虚拟环境设置脚本 功能: - 创建Python虚拟环境 - 安装项目依赖 - 生成激活脚本 用法: python setup_venv.py # 创建venv并安装依赖 python setup_venv.py --upgrade # 升级已有依赖 python setup_venv.py --clean # 删除并重新创建venv """ import os import sys import subprocess import argparse from pathlib import Path def run_command(cmd, cwd=None, check=True): """运行命令并显示输出""" print(f"执行: {' '.join(cmd) if isinstance(cmd, list) else cmd}") try: result = subprocess.run( cmd, cwd=cwd, check=check, capture_output=True, text=True, shell=True if isinstance(cmd, str) else False ) if result.stdout: print(result.stdout) return result except subprocess.CalledProcessError as e: print(f"错误: {e}") if e.stderr: print(f"错误输出: {e.stderr}") if check: sys.exit(1) return e def check_python(): """检查Python版本""" version = sys.version_info print(f"Python版本: {version.major}.{version.minor}.{version.micro}") if version.major < 3 or (version.major == 3 and version.minor < 8): print("❌ 需要Python 3.8或更高版本") sys.exit(1) print("✓ Python版本符合要求") def create_venv(venv_path, clean=False): """创建虚拟环境""" if clean and venv_path.exists(): print(f"删除现有虚拟环境: {venv_path}") import shutil shutil.rmtree(venv_path) if venv_path.exists(): print(f"✓ 虚拟环境已存在: {venv_path}") return print(f"创建虚拟环境: {venv_path}") run_command([sys.executable, "-m", "venv", str(venv_path)]) print("✓ 虚拟环境创建成功") def get_venv_python(venv_path): """获取虚拟环境中的Python路径""" if os.name == 'nt': # Windows return venv_path / "Scripts" / "python.exe" else: # Unix/Linux/macOS return venv_path / "bin" / "python" def get_venv_pip(venv_path): """获取虚拟环境中的pip路径""" if os.name == 'nt': # Windows return venv_path / "Scripts" / "pip.exe" else: # Unix/Linux/macOS return venv_path / "bin" / "pip" def install_dependencies(venv_path, upgrade=False): """安装项目依赖""" python_path = get_venv_python(venv_path) # 升级pip (使用python -m pip方式) print("升级pip...") run_command([str(python_path), "-m", "pip", "install", "--upgrade", "pip"]) # 安装依赖 requirements_file = Path("requirements.txt") if not requirements_file.exists(): print("❌ requirements.txt文件不存在") return print("安装项目依赖...") cmd = [str(python_path), "-m", "pip", "install", "-r", "requirements.txt"] if upgrade: cmd.append("--upgrade") run_command(cmd) print("✓ 依赖安装完成") def create_activation_scripts(venv_path): """创建激活脚本""" backend_dir = Path.cwd() # Windows批处理脚本 activate_bat = backend_dir / "activate_venv.bat" with open(activate_bat, 'w', encoding='utf-8') as f: f.write(f"""@echo off echo 激活Python虚拟环境... call "{venv_path}\\Scripts\\activate.bat" echo ✓ 虚拟环境已激活 echo. echo 可用命令: echo python run.py - 启动Flask应用 echo python init_db.py - 初始化数据库 echo celery -A celery_worker worker - 启动Celery worker echo pytest - 运行测试 echo. """) # Unix/Linux shell脚本 activate_sh = backend_dir / "activate_venv.sh" with open(activate_sh, 'w', encoding='utf-8') as f: f.write(f"""#!/bin/bash echo "激活Python虚拟环境..." source "{venv_path}/bin/activate" echo "✓ 虚拟环境已激活" echo "" echo "可用命令:" echo " python run.py - 启动Flask应用" echo " python init_db.py - 初始化数据库" echo " celery -A celery_worker worker - 启动Celery worker" echo " pytest - 运行测试" echo "" """) # 设置执行权限 (Unix/Linux) if os.name != 'nt': os.chmod(activate_sh, 0o755) print(f"✓ 激活脚本已创建:") print(f" Windows: {activate_bat}") print(f" Unix/Linux: {activate_sh}") def main(): parser = argparse.ArgumentParser(description='Python虚拟环境设置') parser.add_argument('--upgrade', action='store_true', help='升级依赖包') parser.add_argument('--clean', action='store_true', help='删除并重新创建虚拟环境') parser.add_argument('--venv-name', default='venv', help='虚拟环境目录名 (默认: venv)') args = parser.parse_args() print(f"\n{'='*50}") print("Python虚拟环境设置") print(f"{'='*50}\n") # 检查Python版本 check_python() # 虚拟环境路径 venv_path = Path.cwd() / args.venv_name # 创建虚拟环境 create_venv(venv_path, clean=args.clean) # 安装依赖 install_dependencies(venv_path, upgrade=args.upgrade) # 创建激活脚本 create_activation_scripts(venv_path) print(f"\n{'='*50}") print("✓ 虚拟环境设置完成!") print(f"{'='*50}") print(f"\n激活虚拟环境:") if os.name == 'nt': # Windows print(f" activate_venv.bat") print(f" 或者: {venv_path}\\Scripts\\activate.bat") else: # Unix/Linux print(f" source activate_venv.sh") print(f" 或者: source {venv_path}/bin/activate") print(f"\n停用虚拟环境:") print(f" deactivate") if __name__ == '__main__': main()