python-enviroment-install.py 10 KB

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