Files
HeurAMS/src/heurams/services/config.py
2025-11-10 03:01:42 +08:00

47 lines
1.4 KiB
Python

# 配置文件服务
import pathlib
import toml
import typing
class ConfigFile:
def __init__(self, path: pathlib.Path):
self.path = path
if not self.path.exists():
self.path.touch()
self.data = dict()
self._load()
def _load(self):
"""从文件加载配置数据"""
with open(self.path, 'r') as f:
try:
self.data = toml.load(f)
except toml.TomlDecodeError as e:
print(f"{e}")
self.data = {}
def modify(self, key: str, value: typing.Any):
"""修改配置值并保存"""
self.data[key] = value
self.save()
def save(self, path: typing.Union[str, pathlib.Path] = ""):
"""保存配置到文件"""
save_path = pathlib.Path(path) if path else self.path
with open(save_path, 'w') as f:
toml.dump(self.data, f)
def get(self, key: str, default: typing.Any = None) -> typing.Any:
"""获取配置值,如果不存在返回默认值"""
return self.data.get(key, default)
def __getitem__(self, key: str) -> typing.Any:
return self.data[key]
def __setitem__(self, key: str, value: typing.Any):
self.data[key] = value
self.save()
def __contains__(self, key: str) -> bool:
"""支持 in 语法"""
return key in self.data