重置QGIS实现
This commit is contained in:
@@ -5,13 +5,12 @@ QGIS 环境检测与子进程配置模块。
|
||||
所有 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 的路径
|
||||
- get_qgis_python_path(): 检测 QGIS Python 3.12 解释器路径
|
||||
- build_qgis_subprocess_env(): 构建子进程完整环境变量(替代 bat 包装器)
|
||||
- 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
|
||||
@@ -72,31 +71,96 @@ def get_qgis_python_path(qgis_root: str = None) -> str | None:
|
||||
return None
|
||||
|
||||
|
||||
def build_qgis_command(qgis_root: str = None) -> list[str]:
|
||||
def build_qgis_subprocess_env(qgis_root: str = None) -> dict:
|
||||
"""
|
||||
构建通过 .bat 包装器启动 QGIS 子进程的命令列表。
|
||||
设置环境变量并启动 QGIS Python 3.12。
|
||||
构建 QGIS Python 3.12 子进程的完整环境变量(替代 bat 包装器)。
|
||||
|
||||
策略:
|
||||
1. 从 os.environ 继承,移除 venv 污染(PYTHONPATH/VIRTUAL_ENV 等)
|
||||
2. 将 QGIS 的 bin 目录前置到 PATH(Qt5→qgis→gdal 顺序,与原 bat 一致)
|
||||
3. 设置 PYTHONPATH / QGIS_PREFIX_PATH / QT_PLUGIN_PATH / GDAL_DATA / PROJ_DATA
|
||||
4. 子进程 _setup_environment() 负责 os.add_dll_directory + ctypes 预加载
|
||||
"""
|
||||
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()]
|
||||
|
||||
# 继承当前环境,清理 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 安装路径
|
||||
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 解释器")
|
||||
env["QGIS_ROOT"] = qgis_root
|
||||
|
||||
runner_script = get_runner_script()
|
||||
if not os.path.isfile(runner_script):
|
||||
raise RuntimeError(f"QGIS Runner 脚本不存在: {runner_script}")
|
||||
if platform.system() != "Windows":
|
||||
return env
|
||||
|
||||
bat_path = _generate_bat_wrapper(qgis_root, python_path, runner_script)
|
||||
return ["cmd.exe", "/c", bat_path]
|
||||
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")
|
||||
if not os.path.isdir(qgis_app_dir):
|
||||
raise RuntimeError(
|
||||
f"未找到 QGIS 应用目录: {qgis_root}\\apps\\qgis-ltr 或 qgis"
|
||||
)
|
||||
|
||||
# 前置 QGIS bin 目录到 PATH(Qt5 必须在最前面,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 (
|
||||
os.path.join(qgis_app_dir, "share", "proj"),
|
||||
os.path.join(qgis_root, "share", "proj"),
|
||||
os.path.join(qgis_root, "apps", "gdal", "share", "proj"),
|
||||
):
|
||||
if os.path.isfile(os.path.join(pd, "proj.db")):
|
||||
env["PROJ_DATA"] = pd
|
||||
break
|
||||
|
||||
# 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:
|
||||
@@ -109,60 +173,6 @@ def get_runner_script() -> str:
|
||||
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 应用目录(qgis-ltr 或 qgis)
|
||||
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")
|
||||
qgis_app_dir = qgis_app_dir.replace("/", "\\")
|
||||
|
||||
# 自动检测 PROJ 目录
|
||||
proj_data = ""
|
||||
for pd in [
|
||||
os.path.join(qgis_app_dir, "share", "proj"),
|
||||
os.path.join(qgis_root, "share", "proj"),
|
||||
os.path.join(qgis_root, "apps", "gdal", "share", "proj"),
|
||||
]:
|
||||
if os.path.isfile(os.path.join(pd, "proj.db")):
|
||||
proj_data = pd.replace("/", "\\")
|
||||
break
|
||||
|
||||
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("/", "\\")
|
||||
|
||||
proj_line = f'set "PROJ_DATA={proj_data}"' if proj_data else "REM PROJ_DATA not found"
|
||||
|
||||
bat_content = f"""@echo off
|
||||
chcp 65001 >nul
|
||||
set "PYTHONPATH={qgis_python_dir}"
|
||||
set "QGIS_PREFIX_PATH={qgis_app_dir}"
|
||||
set "QT_PLUGIN_PATH={qtplugins};{qt5_plugins}"
|
||||
set "GDAL_DATA={gdal_data}"
|
||||
{proj_line}
|
||||
set "PYTHONUTF8=1"
|
||||
set "GDAL_FILENAME_IS_UTF8=YES"
|
||||
set "VSI_CACHE=TRUE"
|
||||
set "VSI_CACHE_SIZE=1000000"
|
||||
set "PATH={qt5_bin};{qgis_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 安装根目录。
|
||||
|
||||
Reference in New Issue
Block a user