import os
from configparser import ConfigParser
from conf import constant
class MyConfig:
"""定义一个配置文件类读取日志的配置信息"""
def __init__(self, file_name):
"""@file_name:文件路径"""
self.file_name = file_name
self.cp = ConfigParser()
self.cp.read(file_name, encoding="utf-8")
def read_value(self, section, option):
try:
res = self.cp[section][option]
return res
except KeyError as e:
print(f"读取{self.file_name}-》{section}下的{option}配置文件错误! 错误信息:{e}")
def read_int(self, section, option):
"""读取option的值value 得到【int】类型的值"""
res = self.cp.getint(section, option)
return res
def new_section_option(self, section, option, value):
"""添加section,或option,若不存在则会创建"""
if not self.cp.has_section(section):
self.cp.add_section(section)
if not self.cp.has_option(section, option):
self.cp[section][option] = value
with open(self.file_name, "w", encoding="utf-8") as f:
self.cp.write(f)
def amend_option(self, section, option, value):
"""修改某个option的值若不存在则会创建"""
self.cp.set(section, option, value)
with open(self.file_name, "w", encoding="utf-8") as f:
self.cp.write(f)
config = MyConfig(os.path.join(constant.CONFIG_PATH, "config.ini"))
if __name__ == '__main__':
print(config.read_value("LOG", "log_grade"))