python-enviroment-install.py 12 KB

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