""" 2026/4/7 TMY 导入INI文件配置 """ """ #2026/4/18停用,因为打包后不能扎到正确的config路径 import configparser import os class ConfigLoader: _instance = None def __new__(cls): if cls._instance is None: cls._instance = super().__new__(cls) cls._instance.load() return cls._instance def load(self): self.cf = configparser.ConfigParser() self.cf.read(os.path.join(os.path.dirname(__file__), "config.ini"), encoding="utf-8") def get(self, section, key, default=""): try: return self.cf.get(section, key) except: return default def get_int(self, section, key, default=0): try: return self.cf.getint(section, key) except: return default # 全局单例(全项目共用这一个) cfg = ConfigLoader() """ """ 2026/4/18 TMY 导入config.ini文件配置 把读取配置文件的路径改成 exe 真实目录 """ import configparser import os import sys class ConfigLoader: _instance = None def __new__(cls): if cls._instance is None: cls._instance = super().__new__(cls) cls._instance.load() return cls._instance def get_exe_dir(self): # 获取 exe 所在真实目录(不管在哪运行都正确) if getattr(sys, 'frozen', False): # 打包后 return os.path.dirname(sys.executable) else: # 开发环境 return os.path.dirname(__file__) def load(self): self.cf = configparser.ConfigParser() # 关键:从 exe 同级目录读取 config.ini config_path = os.path.join(self.get_exe_dir(), "config.ini") self.cf.read(config_path, encoding="utf-8") def get(self, section, key, default=""): try: return self.cf.get(section, key) except: return default def get_int(self, section, key, default=0): try: return self.cf.getint(section, key) except: return default cfg = ConfigLoader()