pathutils.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. # @description:
  2. # @author: licanglong
  3. # @date: 2025/10/11 10:45
  4. import logging
  5. import os
  6. import sys
  7. from typing import Optional
  8. _log = logging.getLogger(__name__)
  9. def getpath(path: str, raise_error=True) -> Optional[str]:
  10. """
  11. 获取资源绝对路径,支持开发环境和多种打包工具。
  12. params: path (str): 资源路径(绝对或相对)
  13. return: str: 资源绝对路径
  14. """
  15. if not path:
  16. _log.warning("path is empty")
  17. if raise_error:
  18. raise ValueError("path is empty")
  19. return None
  20. path = os.path.normpath(path)
  21. # 绝对路径直接返回
  22. if os.path.isabs(path):
  23. abs_path = path
  24. else:
  25. # 判断打包环境
  26. if getattr(sys, "frozen", False):
  27. # PyInstaller/Nuitka/PyOxidizer 单文件模式
  28. base_path = getattr(sys, "_MEIPASS", os.path.dirname(sys.executable))
  29. else:
  30. # 开发环境:APP_PATH 或当前脚本目录
  31. base_path = os.getenv("APP_PATH", os.path.dirname(os.path.abspath(__file__)))
  32. abs_path = os.path.join(base_path, path)
  33. abs_path = os.path.normpath(abs_path)
  34. # 检查路径存在性(读资源时启用)
  35. if not os.path.exists(abs_path) and raise_error:
  36. if raise_error:
  37. raise FileNotFoundError(abs_path)
  38. return None
  39. return abs_path