Files
xian_algorithm_new/app/services/qgis/qgis_env.py
T
2026-06-20 17:13:52 +08:00

174 lines
6.1 KiB
Python

"""
QGIS 环境检测与子进程配置模块。
主进程运行在 Python 3.10,无法直接加载 QGIS 的 Python 3.12 C 扩展。
所有 QGIS 操作通过 subprocess 调用 QGIS Python 3.12 执行。
本模块提供:
- get_qgis_python_path(): 检测 QGIS Python 3.12 解释器路径
- build_qgis_command(): 构建通过 .bat 启动 QGIS 子进程的命令
- is_qgis_available(): 检查 QGIS 是否可用
- get_runner_script(): 获取 qgis_runner.py 的路径
"""
import os
import tempfile
from pathlib import Path
from app.config.paths import get_logger
logger = get_logger("qgis.env")
def get_qgis_python_path(qgis_root: str = None) -> str | None:
"""
检测 QGIS 自带的 Python 3.12 解释器路径。
Windows: {QGIS_ROOT}/apps/Python312/python3.exe
Returns:
解释器绝对路径,不存在则返回 None
"""
if qgis_root is None:
qgis_root = _detect_qgis_root()
if qgis_root is None:
return None
import platform
if platform.system() == "Windows":
for name in ("python3.exe", "python.exe"):
candidate = os.path.join(qgis_root, "apps", "Python312", name)
if os.path.isfile(candidate):
logger.info(f"检测到 QGIS Python: {candidate}")
return candidate
logger.warning(f"未找到 QGIS Python 3.12")
return None
else:
import shutil
# 优先检查环境变量
env_python = os.environ.get("QGIS_PYTHON_PATH")
if env_python and os.path.isfile(env_python):
logger.info(f"QGIS_PYTHON_PATH 指定: {env_python}")
return env_python
# 搜索标准 Linux QGIS 安装路径
linux_paths = [
"/usr/bin/qgis", # Ubuntu/Debian apt 安装
"/usr/bin/qgis.bin",
"/opt/QGIS/apps/Python312/bin/python3", # 独立安装器
"/opt/QGIS/apps/Python3/bin/python3",
"/usr/libexec/qgis/python3", # Fedora/RHEL
]
for candidate in linux_paths:
if os.path.isfile(candidate):
logger.info(f"检测到 QGIS 可执行文件: {candidate}")
return candidate
# 回退到系统 Python(如果 qgis.core 可导入)
sys_python = shutil.which("python3") or shutil.which("python")
if sys_python:
logger.info(f"Linux 环境,使用系统 Python: {sys_python}")
return sys_python
return None
def build_qgis_command(qgis_root: str = None) -> list[str]:
"""
构建通过 .bat 包装器启动 QGIS 子进程的命令列表。
设置环境变量并启动 QGIS Python 3.12。
"""
import platform
if platform.system() != "Windows":
python_path = get_qgis_python_path(qgis_root)
if not python_path:
raise RuntimeError("未找到 QGIS Python 解释器")
return [python_path, get_runner_script()]
if qgis_root is None:
qgis_root = _detect_qgis_root() or "D:/QGIS"
python_path = get_qgis_python_path(qgis_root)
if not python_path:
raise RuntimeError("未找到 QGIS Python 3.12 解释器")
runner_script = get_runner_script()
if not os.path.isfile(runner_script):
raise RuntimeError(f"QGIS Runner 脚本不存在: {runner_script}")
bat_path = _generate_bat_wrapper(qgis_root, python_path, runner_script)
return ["cmd.exe", "/c", bat_path]
def is_qgis_available(qgis_root: str = None) -> bool:
"""检查 QGIS 环境是否可用"""
return get_qgis_python_path(qgis_root) is not None
def get_runner_script() -> str:
"""获取 qgis_runner.py 的绝对路径"""
return str(Path(__file__).parent / "qgis_runner.py")
def _generate_bat_wrapper(qgis_root: str, python_path: str, runner_script: str) -> str:
"""生成 .bat 包装脚本,设置 QGIS 环境变量并启动 runner"""
qgis_app_dir = os.path.join(qgis_root, "apps", "qgis-ltr").replace("/", "\\")
python_dir = os.path.join(qgis_root, "apps", "Python312").replace("/", "\\")
qt5_plugins = os.path.join(qgis_root, "apps", "Qt5", "plugins").replace("/", "\\")
qtplugins = os.path.join(qgis_app_dir, "qtplugins").replace("/", "\\")
gdal_data = os.path.join(qgis_root, "apps", "gdal", "share", "gdal").replace("/", "\\")
qgis_python_dir = os.path.join(qgis_app_dir, "python").replace("/", "\\")
qgis_bin = os.path.join(qgis_app_dir, "bin").replace("/", "\\")
qt5_bin = os.path.join(qgis_root, "apps", "Qt5", "bin").replace("/", "\\")
gdal_lib = os.path.join(qgis_root, "apps", "gdal", "lib").replace("/", "\\")
bat_content = f"""@echo off
set "PYTHONHOME={python_dir}"
set "PYTHONPATH={qgis_python_dir}"
set "QGIS_PREFIX_PATH={qgis_app_dir}"
set "QT_PLUGIN_PATH={qtplugins};{qt5_plugins}"
set "GDAL_DATA={gdal_data}"
set "PYTHONUTF8=1"
set "GDAL_FILENAME_IS_UTF8=YES"
set "VSI_CACHE=TRUE"
set "VSI_CACHE_SIZE=1000000"
set "PATH={qgis_bin};{qt5_bin};{gdal_lib};%PATH%"
"{python_path}" "{runner_script}" %*
"""
bat_dir = os.path.join(tempfile.gettempdir(), "qgis_runner")
os.makedirs(bat_dir, exist_ok=True)
bat_path = os.path.join(bat_dir, "run_qgis.bat")
with open(bat_path, "w", encoding="utf-8") as f:
f.write(bat_content)
logger.debug(f"生成 QGIS 包装脚本: {bat_path}")
return bat_path
def _detect_qgis_root() -> str | None:
"""
自动检测 QGIS 安装根目录。
优先级:
1. 环境变量 QGIS_ROOT
2. Windows 默认路径 D:/QGIS
3. Linux 常见路径
"""
env_root = os.environ.get("QGIS_ROOT")
if env_root and os.path.isdir(env_root):
return env_root
import platform
if platform.system() == "Windows":
for candidate in ["D:/QGIS", "C:/OSGeo4W", "C:/QGIS"]:
if os.path.isdir(candidate):
logger.info(f"检测到 QGIS 根目录: {candidate}")
return candidate
else:
for candidate in ["/usr", "/opt/QGIS", "/home/QGIS"]:
if os.path.isdir(candidate):
logger.info(f"检测到 QGIS 根目录: {candidate}")
return candidate
logger.warning("未检测到 QGIS 安装目录")
return None