# config_manager.py
|
import os
|
import json
|
import logging
|
import sys
|
from config import Config
|
|
|
class ConfigManager:
|
_instance = None
|
config = None
|
|
def __new__(cls):
|
if cls._instance is None:
|
cls._instance = super(ConfigManager, cls).__new__(cls)
|
cls._instance._init_config()
|
return cls._instance
|
|
def _init_config(self):
|
"""初始化配置,优先使用外部JSON配置覆盖默认值"""
|
# 1. 加载默认配置
|
self.config = Config()
|
|
# 2. 查找配置文件
|
config_path = self._find_config_file()
|
|
# 3. 加载并覆盖配置
|
if config_path:
|
try:
|
with open(config_path, 'r', encoding='utf-8') as f:
|
user_config = json.load(f)
|
self._update_config(user_config)
|
logging.info(f"成功加载外部配置文件: {config_path}")
|
except Exception as e:
|
logging.error(f"加载配置文件失败: {str(e)}")
|
else:
|
logging.warning("未找到外部配置文件,使用默认配置")
|
|
def _find_config_file(self):
|
"""查找配置文件的优先级"""
|
search_paths = [
|
"config.json", # 当前目录
|
os.path.join(os.path.dirname(sys.executable), "config.json") if getattr(sys, 'frozen', False) else None,
|
# EXE目录
|
os.path.expanduser("~/.config/yourapp/config.json"), # 用户配置目录
|
"/etc/yourapp/config.json" # 系统配置目录
|
]
|
|
# 过滤掉None值并保留有效路径
|
valid_paths = [p for p in search_paths if p is not None]
|
|
for path in valid_paths:
|
if os.path.exists(path):
|
return path
|
return None
|
|
def _update_config(self, user_config):
|
"""用JSON配置更新默认配置"""
|
for key, value in user_config.items():
|
if hasattr(self.config, key):
|
setattr(self.config, key, value)
|
else:
|
logging.warning(f"配置文件中存在未知配置项: {key}")
|
|
def get_config(self):
|
"""获取配置对象"""
|
return self.config
|
|
|
# 创建全局实例
|
global_config = ConfigManager()
|