1.效果如下:
2.代码如下:
from configparser import ConfigParser
import threading
class Config():
_instance_lock = threading.Lock()
@classmethod
def instance(cls, *args, **kwargs):
if not hasattr(Config, "_instance"):
with Config._instance_lock:
if not hasattr(Config, "_instance"):
Config._instance = Config(*args, **kwargs)
return Config._instance
def __init__(self) -> None:
self.config=ConfigParser()
self.configpath='./AppConfigs.ini'
self.config.read(self.configpath,encoding='utf-8')
self.sec_appsetting='appSettings'
def getconfig_appSettings(self,key,defualt_value):
'''
读取配置
'''
self.config.read(self.configpath,encoding='utf-8')
if not self.config.has_option(self.sec_appsetting,key):
return defualt_value
else:
return self.config.get(self.sec_appsetting,key)
def setconfig_appSettings(self, key,value):
'''写入(更新)配置文件'''
if not self.config.has_section(self.sec_appsetting):
self.config.add_section(self.sec_appsetting)
self.config.set(self.sec_appsetting, key, value)
with open(self.configpath, 'w') as configfile:
self.config.write(configfile)
def testconfig():
config= Config.instance()
config.setconfig_appSettings("key1","value1")
config.setconfig_appSettings("key2","value2")
realkey=config.getconfig_appSettings('key2','defualt')
realkey2=config.getconfig_appSettings('key1','defualt1')
print(realkey,realkey2+";")
if __name__ == '__main__':
testconfig()