You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
64 lines
2.3 KiB
64 lines
2.3 KiB
import json
|
|
import os
|
|
import logging
|
|
|
|
|
|
class ConfigManager:
|
|
def __init__(self, config_dir="config"):
|
|
self.config_dir = config_dir
|
|
self.presets_file = os.path.join(config_dir, "presets.json")
|
|
|
|
# 确保目录存在
|
|
if not os.path.exists(config_dir):
|
|
os.makedirs(config_dir)
|
|
logging.info(f"创建配置目录: {config_dir}")
|
|
|
|
def save_presets(self, preset_list):
|
|
"""
|
|
保存预案列表到文件
|
|
:param preset_list: 包含字典的列表,每个字典代表一个预案
|
|
"""
|
|
try:
|
|
# 👇 关键点:确保文件夹存在
|
|
if not os.path.exists(self.config_dir):
|
|
os.makedirs(self.config_dir)
|
|
|
|
with open(self.presets_file, 'w', encoding='utf-8') as f:
|
|
# 👇 关键点:ensure_ascii=False 才能保存中文,indent=4 让文件好看一点
|
|
json.dump(preset_list, f, ensure_ascii=False, indent=4)
|
|
logging.info(f"✅ 成功保存配置到 {self.presets_file}")
|
|
return True
|
|
except Exception as e:
|
|
logging.error(f"❌ 保存配置失败: {e}")
|
|
return False
|
|
|
|
def load_presets(self):
|
|
"""
|
|
从文件加载预案列表
|
|
:return: 预案列表 (list)
|
|
"""
|
|
# 👇 关键点:先检查文件是否存在
|
|
if not os.path.exists(self.presets_file):
|
|
logging.warning("⚠️ 配置文件不存在,返回空列表")
|
|
return []
|
|
|
|
try:
|
|
with open(self.presets_file, 'r', encoding='utf-8') as f:
|
|
data = json.load(f)
|
|
logging.info(f"✅ 成功加载配置,共 {len(data)} 条")
|
|
return data
|
|
except Exception as e:
|
|
logging.error(f"❌ 读取配置文件失败: {e}")
|
|
return []
|
|
|
|
|
|
# --- 调试用:如果你直接运行这个文件,会生成一个测试文件 ---
|
|
if __name__ == "__main__":
|
|
# 测试代码:手动创建一个配置管理器并保存测试数据
|
|
cm = ConfigManager()
|
|
test_data = [
|
|
{"name": "测试全屏", "start": 0, "h": 2, "v": 2},
|
|
{"name": "测试单屏", "start": 1, "h": 1, "v": 1}
|
|
]
|
|
cm.save_presets(test_data)
|
|
print("测试配置已生成,请检查 config/presets.json 文件")
|