python-enviroment-install.py 14 KB

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