Files
xian_algorithm_new/app/services/qgis/qgis_env.py
T

203 lines
6.7 KiB
Python
Raw Normal View History

2026-06-19 17:04:03 +08:00
"""
2026-06-20 15:50:24 +08:00
QGIS 环境检测与子进程配置模块。
主进程运行在 Python 3.10,无法直接加载 QGIS 的 Python 3.12 C 扩展。
所有 QGIS 操作通过 subprocess 调用 QGIS Python 3.12 执行。
本模块提供:
2026-06-21 12:47:43 +08:00
- get_qgis_python_path(): 检测 QGIS Python 3.12 解释器路径
- build_qgis_subprocess_env(): 构建子进程完整环境变量(替代 bat 包装器)
- is_qgis_available(): 检查 QGIS 是否可用
- get_runner_script(): 获取 qgis_runner.py 的路径
2026-06-19 17:04:03 +08:00
"""
import os
from pathlib import Path
from app.config.paths import get_logger
logger = get_logger("qgis.env")
2026-06-20 15:50:24 +08:00
def get_qgis_python_path(qgis_root: str = None) -> str | None:
2026-06-19 17:04:03 +08:00
"""
2026-06-20 15:50:24 +08:00
检测 QGIS 自带的 Python 3.12 解释器路径。
2026-06-19 17:04:03 +08:00
2026-06-20 15:50:24 +08:00
Windows: {QGIS_ROOT}/apps/Python312/python3.exe
2026-06-19 17:04:03 +08:00
2026-06-20 15:50:24 +08:00
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
2026-06-19 17:04:03 +08:00
2026-06-20 15:50:24 +08:00
# 回退到系统 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
2026-06-19 17:04:03 +08:00
2026-06-21 12:47:43 +08:00
def build_qgis_subprocess_env(qgis_root: str = None) -> dict:
2026-06-20 15:50:24 +08:00
"""
2026-06-21 12:47:43 +08:00
构建 QGIS Python 3.12 子进程的完整环境变量(替代 bat 包装器)。
策略:
1. 从 os.environ 继承,移除 venv 污染(PYTHONPATH/VIRTUAL_ENV 等)
2. 将 QGIS 的 bin 目录前置到 PATHQt5→qgis→gdal 顺序,与原 bat 一致)
3. 设置 PYTHONPATH / QGIS_PREFIX_PATH / QT_PLUGIN_PATH / GDAL_DATA / PROJ_DATA
4. 子进程 _setup_environment() 负责 os.add_dll_directory + ctypes 预加载
2026-06-20 15:50:24 +08:00
"""
import platform
2026-06-20 17:13:52 +08:00
2026-06-21 12:47:43 +08:00
# 继承当前环境,清理 venv 污染
env = dict(os.environ)
venv_root = env.get("VIRTUAL_ENV", "").lower()
for key in (
"PYTHONPATH",
"PYTHONHOME",
"VIRTUAL_ENV",
"PYTHONDONTWRITEBYTECODE",
):
env.pop(key, None)
if venv_root:
path_parts = env.get("PATH", "").split(";")
clean = []
for p in path_parts:
if not p or venv_root in p.lower():
continue
clean.append(p)
env["PATH"] = ";".join(clean)
# 检测 QGIS 安装路径
2026-06-20 15:50:24 +08:00
if qgis_root is None:
qgis_root = _detect_qgis_root() or "D:/QGIS"
2026-06-19 17:04:03 +08:00
2026-06-21 12:47:43 +08:00
env["QGIS_ROOT"] = qgis_root
2026-06-19 17:04:03 +08:00
2026-06-21 12:47:43 +08:00
if platform.system() != "Windows":
return env
2026-06-19 17:04:03 +08:00
2026-06-20 17:20:36 +08:00
qgis_app_dir = os.path.join(qgis_root, "apps", "qgis-ltr")
if not os.path.isdir(qgis_app_dir):
qgis_app_dir = os.path.join(qgis_root, "apps", "qgis")
2026-06-21 12:47:43 +08:00
if not os.path.isdir(qgis_app_dir):
raise RuntimeError(
f"未找到 QGIS 应用目录: {qgis_root}\\apps\\qgis-ltr 或 qgis"
)
# 前置 QGIS bin 目录到 PATHQt5 必须在最前面,QGIS 依赖它)
qgis_bin = os.path.join(qgis_app_dir, "bin")
qt5_bin = os.path.join(qgis_root, "apps", "Qt5", "bin")
gdal_lib = os.path.join(qgis_root, "apps", "gdal", "lib")
qt5_plugins = os.path.join(qgis_root, "apps", "Qt5", "plugins")
qtplugins = os.path.join(qgis_app_dir, "qtplugins")
qgis_python_dir = os.path.join(qgis_app_dir, "python")
env["PATH"] = f"{qt5_bin};{qgis_bin};{gdal_lib};{env.get('PATH', '')}"
# QGIS 核心环境变量(与 bat 包装器保持一致)
env["PYTHONPATH"] = qgis_python_dir
env["QGIS_PREFIX_PATH"] = qgis_app_dir
env["QT_PLUGIN_PATH"] = f"{qtplugins};{qt5_plugins}"
# GDAL / PROJ 数据目录(避免系统旧版 proj.db 干扰)
gdal_data = os.path.join(qgis_root, "apps", "gdal", "share", "gdal")
if os.path.isdir(gdal_data):
env["GDAL_DATA"] = gdal_data
for pd in (
2026-06-20 17:20:36 +08:00
os.path.join(qgis_app_dir, "share", "proj"),
os.path.join(qgis_root, "share", "proj"),
os.path.join(qgis_root, "apps", "gdal", "share", "proj"),
2026-06-21 12:47:43 +08:00
):
2026-06-20 17:20:36 +08:00
if os.path.isfile(os.path.join(pd, "proj.db")):
2026-06-21 12:47:43 +08:00
env["PROJ_DATA"] = pd
2026-06-20 17:20:36 +08:00
break
2026-06-21 12:47:43 +08:00
# UTF-8 / GDAL 编码辅助变量
env["PYTHONUTF8"] = "1"
env["GDAL_FILENAME_IS_UTF8"] = "YES"
env["VSI_CACHE"] = "TRUE"
env["VSI_CACHE_SIZE"] = "1000000"
logger.debug(
f"QGIS subprocess env built: root={qgis_root}, app={qgis_app_dir}, "
f"PATH prefixed with qgis_bin/qt5_bin/gdal_lib"
)
return env
def is_qgis_available(qgis_root: str = None) -> bool:
"""检查 QGIS 环境是否可用"""
return get_qgis_python_path(qgis_root) is not None
2026-06-20 17:13:52 +08:00
2026-06-21 12:47:43 +08:00
def get_runner_script() -> str:
"""获取 qgis_runner.py 的绝对路径"""
return str(Path(__file__).parent / "qgis_runner.py")
2026-06-20 17:13:52 +08:00
2026-06-20 15:50:24 +08:00
def _detect_qgis_root() -> str | None:
2026-06-19 17:04:03 +08:00
"""
2026-06-20 15:50:24 +08:00
自动检测 QGIS 安装根目录。
2026-06-19 17:04:03 +08:00
2026-06-20 15:50:24 +08:00
优先级:
1. 环境变量 QGIS_ROOT
2. Windows 默认路径 D:/QGIS
3. Linux 常见路径
2026-06-19 17:04:03 +08:00
"""
2026-06-20 15:50:24 +08:00
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
2026-06-19 17:04:03 +08:00
else:
2026-06-20 15:50:24 +08:00
for candidate in ["/usr", "/opt/QGIS", "/home/QGIS"]:
if os.path.isdir(candidate):
logger.info(f"检测到 QGIS 根目录: {candidate}")
return candidate
2026-06-19 17:04:03 +08:00
2026-06-20 15:50:24 +08:00
logger.warning("未检测到 QGIS 安装目录")
return None