86 lines
2.3 KiB
Python
86 lines
2.3 KiB
Python
"""
|
||
geo_tools.utils.config
|
||
~~~~~~~~~~~~~~~~~~~~~~
|
||
配置加载辅助函数:读取 TOML / JSON / YAML 格式的任务配置文件。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
from pathlib import Path
|
||
from typing import Any
|
||
|
||
|
||
def load_json_config(path: str | Path) -> dict[str, Any]:
|
||
"""读取 JSON 配置文件。
|
||
|
||
Parameters
|
||
----------
|
||
path:
|
||
JSON 文件路径。
|
||
|
||
Returns
|
||
-------
|
||
dict
|
||
"""
|
||
path = Path(path)
|
||
if not path.exists():
|
||
raise FileNotFoundError(f"配置文件不存在:{path}")
|
||
with path.open(encoding="utf-8") as f:
|
||
return json.load(f)
|
||
|
||
|
||
def load_toml_config(path: str | Path) -> dict[str, Any]:
|
||
"""读取 TOML 配置文件(Python 3.11+ 内置 tomllib,低版本需 tomli)。
|
||
|
||
Parameters
|
||
----------
|
||
path:
|
||
TOML 文件路径。
|
||
"""
|
||
path = Path(path)
|
||
if not path.exists():
|
||
raise FileNotFoundError(f"配置文件不存在:{path}")
|
||
try:
|
||
import tomllib # Python 3.11+
|
||
except ImportError:
|
||
try:
|
||
import tomli as tomllib # type: ignore[no-redef]
|
||
except ImportError as exc:
|
||
raise ImportError(
|
||
"读取 TOML 文件需要 Python 3.11+ 或安装 tomli:pip install tomli"
|
||
) from exc
|
||
with path.open("rb") as f:
|
||
return tomllib.load(f)
|
||
|
||
|
||
def load_yaml_config(path: str | Path) -> dict[str, Any]:
|
||
"""读取 YAML 配置文件(需安装 PyYAML)。"""
|
||
path = Path(path)
|
||
if not path.exists():
|
||
raise FileNotFoundError(f"配置文件不存在:{path}")
|
||
try:
|
||
import yaml
|
||
except ImportError as exc:
|
||
raise ImportError("读取 YAML 文件需要安装 pyyaml:pip install pyyaml") from exc
|
||
with path.open(encoding="utf-8") as f:
|
||
return yaml.safe_load(f) or {}
|
||
|
||
|
||
def load_config(path: str | Path) -> dict[str, Any]:
|
||
"""根据文件扩展名自动选择解析器。
|
||
|
||
支持 ``.json``、``.toml``、``.yaml``、``.yml``。
|
||
"""
|
||
path = Path(path)
|
||
ext = path.suffix.lower()
|
||
loaders = {
|
||
".json": load_json_config,
|
||
".toml": load_toml_config,
|
||
".yaml": load_yaml_config,
|
||
".yml": load_yaml_config,
|
||
}
|
||
if ext not in loaders:
|
||
raise ValueError(f"不支持的配置文件格式:{ext!r},支持:{list(loaders)}")
|
||
return loaders[ext](path)
|