配置文件格式
这里以ini配置文件为例:
[base_info]
version = 20211128
auto = True
start_time = 2021-11-28 18:00:00
[database]
host = xxxxxxx
port = 5432
database = xxx
user = xxx
password = xxxxxxx
ini配置文件由section组成,"[]"内的文字是section的标题,每个section下的键值对记录相应的配置。
读取配置文件
import configparser
def get_conf_obj():
"""
获取conf对象——RawConfigParser()类型
:return: conf对象
"""
parameters_path = "conf/parameters.ini"
conf = configparser.RawConfigParser()
conf.read(parameters_path, encoding="utf-8-sig")
return conf
def get_specified_section(section_name):
"""
获取指定section的信息
:param section_name: 配置文件的section名称
:return: 包含section信息的类对象
"""
try:
conf = get_conf_obj()
section_dict = dict(conf.items(section_name))
return section_dict
except Exception as v:
print(f'读取配置失败:{v}')
调用方式
if __name__ == '__main__':
res = get_specified_section_obj('base_info')
print(res)
print(res['version'])