python 标准库模块 configparser 读取配置文件xxx.cfg的公共方法

import configparser
import os
import collections

config_dir = os.path.dirname(os.path.abspath(__file__))

GLOBAL_CONFIG = {}

def read_config_file(file_name):
    global GLOBAL_CONFIG
    config = configparser.ConfigParser(dict_type=collections.OrderedDict)
    config.optionxform = str
    file_name = os.path.join(config_dir,file_name)
    print(f'Using {file_name}')
    if os.path.exists(file_name):
        config.read(file_name)
    else:
        print(f'{file_name} not exist!')
        exit(1)

    config_dict = {s:dict(config.items(s)) for s in config.sections()}
    print(config_dict)
    GLOBAL_CONFIG.update(config_dict)

xxx.cfg内容格式范例

[section0]
option0 = Hello World
option1 = 1
option2 = 1.0
option3 = false

[section1]
option0 = Hello configparser!
option1 = 2
option2 = 2.0
option3 = true
option4 = option4 created

[new section]
new option = Hi configparser

具体configparser 的用法,请自行百度 

猜你喜欢

转载自blog.csdn.net/weixin_41147796/article/details/136910132