重置QGIS实现

This commit is contained in:
wzy-warehouse
2026-06-21 12:47:43 +08:00
parent 480e793ff8
commit fe3ccd005d
4 changed files with 160 additions and 192 deletions
+46 -30
View File
@@ -379,7 +379,9 @@ def _generate_batch_maps(models: list, config: dict, disaster_time: str) -> None
import json
import subprocess
import tempfile
from app.services.qgis.qgis_env import build_qgis_command
from app.services.qgis.qgis_env import (
get_qgis_python_path, get_runner_script, build_qgis_subprocess_env,
)
try:
logger.info(f"[批量产图] 开始: {len(models)} 张专题图, batch={disaster_time}")
@@ -400,15 +402,19 @@ def _generate_batch_maps(models: list, config: dict, disaster_time: str) -> None
try:
from config import settings
qgis_root = getattr(settings, "QGIS_ROOT", "D:/QGIS")
cmd = build_qgis_command(qgis_root)
cmd.append(tmp_json.name)
python_path = get_qgis_python_path(qgis_root)
if not python_path:
raise RuntimeError("未找到 QGIS Python 3.12 解释器")
runner_script = get_runner_script()
cmd = [python_path, runner_script, tmp_json.name]
logger.info(f"[批量产图] 启动 QGIS 子进程: {' '.join(cmd[:3])}...")
logger.info(f"[批量产图] 启动 QGIS 子进程: {python_path}...")
result = subprocess.run(
cmd,
capture_output=True,
timeout=300, # 5 分钟超时(批量处理多个模板
timeout=600, # 10 分钟超时(15 张模板 × ~40s/张
env=build_qgis_subprocess_env(qgis_root),
)
finally:
try:
@@ -416,7 +422,37 @@ def _generate_batch_maps(models: list, config: dict, disaster_time: str) -> None
except OSError:
pass
if result.returncode != 0:
# 解析子进程输出 —— 优先检查 stdout 是否有有效结果
stdout_text = result.stdout.decode("utf-8", errors="replace").strip()
parsed_output = None
if stdout_text:
for line in reversed(stdout_text.split("\n")):
line = line.strip()
if line.startswith("{"):
try:
parsed_output = json.loads(line)
break
except json.JSONDecodeError:
continue
if parsed_output is not None:
batch_results = parsed_output.get("results", [])
success_count = sum(1 for r in batch_results if "error" not in r)
fail_count = len(batch_results) - success_count
logger.info(
f"[批量产图] 完成: 成功={success_count}, 失败={fail_count}"
)
for r in batch_results:
if "error" not in r:
logger.info(f" OK {r.get('output', 'N/A')}")
else:
logger.error(f" FAIL {r.get('error', 'unknown')}")
if success_count == 0 and fail_count > 0:
first_err = batch_results[0].get("error", "unknown")
raise RuntimeError(
f"QGIS 子进程所有模型均失败 ({fail_count}张): {first_err}"
)
elif result.returncode != 0:
stderr_text = result.stderr.decode("utf-8", errors="replace").strip()
logger.error(f"[批量产图] QGIS 子进程失败 (exit={result.returncode}):")
for line in stderr_text.split("\n"):
@@ -424,35 +460,15 @@ def _generate_batch_maps(models: list, config: dict, disaster_time: str) -> None
raise RuntimeError(
f"QGIS 子进程失败: {stderr_text[:300]}"
)
# 解析子进程输出
stdout_text = result.stdout.decode("utf-8", errors="replace").strip()
if stdout_text:
for line in reversed(stdout_text.split("\n")):
line = line.strip()
if line.startswith("{"):
output = json.loads(line)
batch_results = output.get("results", [])
success_count = sum(1 for r in batch_results if "error" not in r)
fail_count = len(batch_results) - success_count
logger.info(
f"[批量产图] 完成: 成功={success_count}, 失败={fail_count}"
)
for r in batch_results:
if "error" not in r:
logger.info(f" OK {r.get('output', 'N/A')}")
else:
logger.error(f" FAIL {r.get('error', 'unknown')}")
break
else:
logger.warning("[批量产图] 子进程输出中未找到 JSON 结果")
else:
logger.warning("[批量产图] 子进程无输出,exit code = 0")
logger.warning("[批量产图] 子进程无有效输出,exit code = 0")
except subprocess.TimeoutExpired:
logger.error(f"[批量产图] QGIS 子进程超时 (300s)")
logger.error(f"[批量产图] QGIS 子进程超时 (600s)")
raise
except Exception as e:
logger.error(f"[批量产图] 产图失败: {e}", exc_info=True)
raise
# ============================================================