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.
54 lines
1.6 KiB
54 lines
1.6 KiB
#!/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.data = self.read_yaml()
|
|
self.ok = True
|
|
else:
|
|
congif_path = "../" + congif_path
|
|
if os.path.exists(congif_path):
|
|
self.file_path = congif_path
|
|
self.data = self.read_yaml()
|
|
self.ok = True
|
|
else:
|
|
raise Exception('没有找到%s文件路径'%congif_path)
|
|
print("ConfigManager实例化")
|
|
|
|
def __del__(self):
|
|
print("ConfigManager销毁")
|
|
|
|
#已调整方案--配置文件的初始化工作放到构造函数中处理。
|
|
def my_init(self,file_path):
|
|
if os.path.exists(file_path):
|
|
self.file_path = file_path
|
|
self.data = self.read_yaml()
|
|
self.ok = True
|
|
else:
|
|
raise Exception('没有找到%s文件路径'%file_path)
|
|
|
|
def read_yaml(self):
|
|
with open(self.file_path,'r',encoding='utf_8') as f:
|
|
p = f.read()
|
|
return p
|
|
|
|
def get_data(self,pwd=None):
|
|
if self.ok:
|
|
result = yaml.load(self.data,Loader=yaml.FullLoader)
|
|
if pwd == None:
|
|
return result
|
|
else:
|
|
return result.get(pwd)
|
|
|
|
#这种方法实现的单例优点是简单,但不能动态创建实例,程序加载时就已实例化。
|
|
myCongif = ConfigManager()
|
|
|
|
if __name__ == '__main__':
|
|
r = myCongif.get_data('url')
|
|
print(r)
|