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.

56 lines
1.6 KiB

11 months ago
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'ZL'
import yaml,os
class ConfigManager():
def __init__(self,congif_path='config.yaml'):
self.ok = False
10 months ago
11 months ago
if os.path.exists(congif_path):
self.file_path = congif_path
10 months ago
self.ok = self.read_yaml()
11 months ago
else:
congif_path = "../" + congif_path
if os.path.exists(congif_path):
self.file_path = congif_path
10 months ago
self.ok= self.read_yaml()
11 months ago
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:
10 months ago
self.data = yaml.safe_load(f)
return True
return False
11 months ago
10 months ago
'''
.作为层级节点分割符
'''
11 months ago
def get_data(self,pwd=None):
if self.ok:
10 months ago
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
11 months ago
#这种方法实现的单例优点是简单,但不能动态创建实例,程序加载时就已实例化。
myCongif = ConfigManager()
if __name__ == '__main__':
10 months ago
r = myCongif.get_data('mysql.host1')
11 months ago
print(r)