yj
2026-03-31 033d919018b3a3e12755f008c0b9093364942512
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# 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()