python-enviroment-install.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. Python 依赖安装和同步脚本
  5. 功能:检查、安装 Python 依赖到虚拟环境,然后同步所有已安装的包到 environment.txt
  6. """
  7. import os
  8. import sys
  9. import subprocess
  10. import platform
  11. from pathlib import Path
  12. # 获取脚本所在目录和项目根目录
  13. SCRIPT_DIR = Path(__file__).parent.absolute()
  14. PROJECT_ROOT = SCRIPT_DIR.parent.absolute()
  15. VENV_PATH = SCRIPT_DIR / "env"
  16. ENVIRONMENT_FILE = SCRIPT_DIR / "environment.txt"
  17. REQUIREMENTS_FILE = PROJECT_ROOT / "requirements.txt"
  18. # 根据操作系统确定虚拟环境的 Python 和 pip 路径
  19. if platform.system() == "Windows":
  20. VENV_PYTHON = VENV_PATH / "Scripts" / "python.exe"
  21. VENV_PIP = VENV_PATH / "Scripts" / "pip.exe"
  22. else:
  23. VENV_PYTHON = VENV_PATH / "bin" / "python"
  24. VENV_PIP = VENV_PATH / "bin" / "pip"
  25. def run_command(cmd, check=True, capture_output=True):
  26. """运行命令并返回结果"""
  27. try:
  28. result = subprocess.run(
  29. cmd,
  30. shell=True,
  31. check=check,
  32. capture_output=capture_output,
  33. text=True,
  34. encoding='utf-8'
  35. )
  36. return result.returncode == 0, result.stdout, result.stderr
  37. except subprocess.CalledProcessError as e:
  38. return False, e.stdout if hasattr(e, 'stdout') else "", str(e)
  39. def ensure_venv():
  40. """确保虚拟环境存在"""
  41. if not VENV_PATH.exists():
  42. print("[WARN] Virtual environment not found, creating...")
  43. success, _, error = run_command(f'python -m venv "{VENV_PATH}"', check=False)
  44. if not success:
  45. print(f"[X] Failed to create virtual environment: {error}")
  46. sys.exit(1)
  47. print("[OK] Virtual environment created successfully")
  48. return True
  49. def get_venv_pip():
  50. """获取虚拟环境的 pip 命令"""
  51. if platform.system() == "Windows":
  52. return str(VENV_PIP)
  53. else:
  54. return str(VENV_PIP)
  55. def read_dependencies(source_file):
  56. """读取依赖列表"""
  57. if not source_file.exists():
  58. return []
  59. dependencies = []
  60. with open(source_file, 'r', encoding='utf-8') as f:
  61. for line in f:
  62. line = line.strip()
  63. # 跳过注释和空行
  64. if line and not line.startswith('#'):
  65. dependencies.append(line)
  66. return dependencies
  67. def get_installed_packages_from_filesystem():
  68. """直接从文件系统获取已安装的包列表(快速方法)"""
  69. if platform.system() == "Windows":
  70. site_packages = VENV_PATH / "Lib" / "site-packages"
  71. else:
  72. # Linux/Mac: 需要找到 site-packages 路径
  73. import sysconfig
  74. site_packages = Path(sysconfig.get_path('purelib', vars={'base': str(VENV_PATH)}))
  75. installed_packages = set()
  76. if site_packages.exists():
  77. for item in site_packages.iterdir():
  78. if item.is_dir():
  79. pkg_name = item.name
  80. # 处理 .dist-info 和 .egg-info 文件夹(最准确的包名来源)
  81. if pkg_name.endswith('.dist-info'):
  82. # 从 dist-info 文件夹名提取包名(格式:package-name-version.dist-info)
  83. parts = pkg_name.replace('.dist-info', '').rsplit('-', 1)
  84. if len(parts) >= 1:
  85. installed_packages.add(parts[0].lower().replace('_', '-'))
  86. elif pkg_name.endswith('.egg-info'):
  87. # 从 egg-info 文件夹名提取包名
  88. parts = pkg_name.replace('.egg-info', '').rsplit('-', 1)
  89. if len(parts) >= 1:
  90. installed_packages.add(parts[0].lower().replace('_', '-'))
  91. elif pkg_name not in ['__pycache__', 'dist-info', 'egg-info']:
  92. # 检查是否是 Python 包(有 __init__.py 或 .py 文件)
  93. if (item / "__init__.py").exists() or any(item.glob("*.py")):
  94. pkg_lower = pkg_name.lower()
  95. installed_packages.add(pkg_lower)
  96. # 添加下划线和连字符的变体
  97. installed_packages.add(pkg_lower.replace('_', '-'))
  98. installed_packages.add(pkg_lower.replace('-', '_'))
  99. # 特殊映射:opencv-python 安装后显示为 cv2
  100. if 'cv2' in installed_packages:
  101. installed_packages.add('opencv-python')
  102. installed_packages.add('opencv-contrib-python')
  103. installed_packages.add('opencv-python-headless')
  104. return installed_packages
  105. def check_package_installed(package_name, installed_packages_set=None):
  106. """检查包是否已安装(使用文件系统快速检查)"""
  107. # 提取包名(支持 ==, >=, <=, >, <, ~= 等版本操作符)
  108. pkg_name = package_name.split('==')[0].split('>=')[0].split('<=')[0].split('>')[0].split('<')[0].split('~=')[0].strip()
  109. pkg_name_lower = pkg_name.lower()
  110. # 如果没有提供已安装包集合,则获取一次(避免重复调用)
  111. if installed_packages_set is None:
  112. installed_packages_set = get_installed_packages_from_filesystem()
  113. # 快速检查(使用已获取的集合)
  114. return (
  115. pkg_name_lower in installed_packages_set or
  116. pkg_name_lower.replace('-', '_') in installed_packages_set or
  117. pkg_name_lower.replace('_', '-') in installed_packages_set
  118. )
  119. def install_packages(packages, source_file, venv_pip):
  120. """安装包到虚拟环境"""
  121. failed_packages = []
  122. if source_file == REQUIREMENTS_FILE and REQUIREMENTS_FILE.exists():
  123. # 使用 requirements.txt 批量安装
  124. cmd = f'"{venv_pip}" install -r "{source_file}"'
  125. success, _, error = run_command(cmd, check=False)
  126. if not success:
  127. print(f"[X] Installation failed: {error}")
  128. return False, failed_packages
  129. else:
  130. # 逐个安装
  131. for package in packages:
  132. cmd = f'"{venv_pip}" install {package}'
  133. success, _, error = run_command(cmd, check=False)
  134. if not success:
  135. print(f"[X] Failed to install: {package}")
  136. failed_packages.append(package)
  137. if failed_packages:
  138. return False, failed_packages
  139. return True, []
  140. def sync_environment_file(venv_pip, silent=False):
  141. """同步所有已安装的包到 environment.txt"""
  142. cmd = f'"{venv_pip}" freeze'
  143. success, output, error = run_command(cmd, check=False)
  144. if not success:
  145. if not silent:
  146. print(f"[X] Failed to get installed packages list: {error}")
  147. return False
  148. # 使用 UTF-8 无 BOM 编码写入文件
  149. with open(ENVIRONMENT_FILE, 'w', encoding='utf-8', newline='\n') as f:
  150. f.write(output)
  151. if not silent:
  152. package_count = len([line for line in output.strip().split('\n') if line.strip()])
  153. print(f"[OK] All installed packages synced to {ENVIRONMENT_FILE}")
  154. print(f" Total packages: {package_count}")
  155. return True
  156. def main():
  157. """主函数"""
  158. # 确保虚拟环境存在
  159. if not ensure_venv():
  160. sys.exit(1)
  161. venv_pip = get_venv_pip()
  162. # 确定依赖源文件(优先使用 requirements.txt,如果没有则使用 environment.txt)
  163. if REQUIREMENTS_FILE.exists():
  164. source_file = REQUIREMENTS_FILE
  165. elif ENVIRONMENT_FILE.exists():
  166. source_file = ENVIRONMENT_FILE
  167. else:
  168. sync_environment_file(venv_pip)
  169. sys.exit(0)
  170. # 读取依赖列表
  171. required_packages = read_dependencies(source_file)
  172. if not required_packages:
  173. print("[OK] No dependencies specified")
  174. sys.exit(0)
  175. # 快速检查缺失的依赖(使用文件系统)
  176. missing_packages = []
  177. installed_count = 0
  178. missing_count = 0
  179. # 一次性获取所有已安装的包(只检查一次文件系统)
  180. installed_packages_set = get_installed_packages_from_filesystem()
  181. for package in required_packages:
  182. package_line = package.strip()
  183. if not package_line:
  184. continue
  185. # 提取包名
  186. package_name = package_line.split('==')[0].split('>=')[0].split('<=')[0].split('>')[0].split('<')[0].split('~=')[0].strip()
  187. pkg_name_lower = package_name.lower()
  188. # 快速检查(使用已获取的集合)
  189. is_installed = (
  190. pkg_name_lower in installed_packages_set or
  191. pkg_name_lower.replace('-', '_') in installed_packages_set or
  192. pkg_name_lower.replace('_', '-') in installed_packages_set
  193. )
  194. if is_installed:
  195. installed_count += 1
  196. else:
  197. missing_packages.append(package_line)
  198. missing_count += 1
  199. # 如果有缺失的依赖,显示必要信息并安装
  200. if missing_count > 0:
  201. print(f"[X] Missing {missing_count} package(s) out of {len(required_packages)}")
  202. print("Missing packages:")
  203. for missing in missing_packages:
  204. print(f" - {missing}")
  205. print("\nInstalling missing packages...")
  206. success, failed = install_packages(missing_packages, source_file, venv_pip)
  207. if success:
  208. print("[OK] All packages installed successfully")
  209. else:
  210. if failed:
  211. print(f"[X] Failed to install {len(failed)} package(s):")
  212. for pkg in failed:
  213. print(f" - {pkg}")
  214. else:
  215. print("[X] Some packages installation failed")
  216. # 即使有失败,也继续同步已安装的包
  217. print("[WARN] Continuing to sync installed packages...")
  218. # 同步所有已安装的包到 environment.txt
  219. sync_environment_file(venv_pip)
  220. else:
  221. # 所有依赖都齐全时,只显示一行信息(包含同步结果)
  222. sync_environment_file(venv_pip, silent=True)
  223. print(f"[OK] All dependencies are installed ({len(required_packages)} packages)")
  224. sys.exit(0)
  225. if __name__ == "__main__":
  226. main()