#!/usr/bin/env python # -*- coding:utf-8 -*- __author__ = 'ZL' import yaml,os class ConfigManager(): def __init__(self,congif_path='config.yaml'): self.ok = False if os.path.exists(congif_path): self.file_path = congif_path self.ok = self.read_yaml() else: congif_path = "../" + congif_path if os.path.exists(congif_path): self.file_path = congif_path self.ok= self.read_yaml() else: raise Exception('没有找到%s文件路径'%congif_path) print("ConfigManager实例化") def __del__(self): print("ConfigManager销毁") def read_yaml(self): with open(self.file_path,'r',encoding='utf_8') as f: self.data = yaml.safe_load(f) return True return False ''' 以.作为层级节点分割符 ''' def get_data(self,pwd=None): if self.ok: if pwd is None: return None nodes = pwd.split('.') current_node= self.data for node in nodes: if node in current_node: current_node = current_node[node] else: print(f"Node {node} not found in the YAML data.") return None return current_node #这种方法实现的单例优点是简单,但不能动态创建实例,程序加载时就已实例化。 myCongif = ConfigManager() if __name__ == '__main__': r = myCongif.get_data('mysql.host1') print(r)