1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
|
u""" Python 读写 配置文件
逻辑说明: - read_config 读取配置文件入口函数 - read_config_ini - read_config_yaml - write_config 写入配置文件入口函数 - write_config_ini - write_config_yaml - 函数配置调用 - 根据 postfix_func_dict 指定文件后缀调用函数 - 单独指定读取某类文件时,直接传入参数 filename_postfix 即可
支持以下配置文件读写 - *.ini ConfigParser - *.yaml yaml TODO
语法等说明 - ConfigParser - yaml
# 配置文件使用样例 ConfigParser https://www.cnblogs.com/klb561/p/10085328.html
# *.yaml pyyaml pip install pyyaml """
import os import ConfigParser import sys import traceback import logging
import yaml
reload(sys) sys.setdefaultencoding("utf-8")
postfix_func_dict = { '.ini': 'ini', '.yaml': 'yaml', }
default_filename_postfix = '.ini'
ini_config_data = [ {'section': 'scetionA', 'section_vals': [ {'key': '', 'val': '', 'dtype': ''}, {'key': '', 'val': '', 'dtype': ''}, ]} ]
ini_config_data = { 'sectionA': { 'key1': 'val1', 'key2': 'val2', }, 'sectionB': { 'key11': 'val11', 'key21': 'val21', }, }
from collections import OrderedDict
def read_config(config_path, filename_postfix=None): u""" 读取配置文件
:param str config_path: 配置文件路径 :param str filename_postfix: 配置文件类型 ini / yaml """ config_data = OrderedDict(dict()) if not config_path or not os.path.exists(config_path): logging.error("配置文件[%s]为空或不存在", config_path) return config_data
filename_postfix = filename_postfix if filename_postfix else os.path.splitext(config_path)[1] config_data = globals().get('read_config_%s' % postfix_func_dict.get(filename_postfix, default_filename_postfix))( config_path)
logging.info("读取配置文件[%s]成功,配置信息[%s]", config_path, config_data) return config_data
def read_config_yaml(config_path): u""" 读取配置文件
:param str config_path: 配置文件路径
:return: dict config_data """ config_data = OrderedDict(dict()) try: f = open(config_path, 'r') config = f.read() if float(yaml.__version__) <= 5.1: config_data = yaml.load(config) else: config_data = yaml.load(config, Loader=yaml.FullLoader) except Exception as e: logging.error(traceback.format_exc()) logging.error("配置文件[%s]无法正常解析,请检查!", config_path) return config_data
def read_config_ini(config_path): u""" 读取配置文件
:param str config_path: 配置文件路径
:return: dict config_data """ config_data = OrderedDict(dict()) if not config_path or not os.path.exists(config_path): logging.error("配置文件[%s]为空或不存在", config_path) return config_data
try: config = ConfigParser.ConfigParser() config.readfp(open(r'%s' % config_path)) for section in config.sections(): config_data[section] = OrderedDict(dict()) for key, val in config.items(section): config_data[section][key] = val except Exception as e: logging.error(traceback.format_exc()) logging.error("配置文件[%s]无法正常解析,请检查!", config_path) return config_data
def write_config(config_path, config_data, filename_postfix=None, mode='a', funcname=None): u""" 写入配置文件
:param str config_path: 配置文件 :param dict config_data: 配置字典 :param str filename_postfix: 配置文件类型 ini / yaml . 为空时自动读取文件名称后缀,根据不同后缀调用不同函数 :param str mode: 数据时 追加写入还是覆盖等 a w """
filename_postfix = filename_postfix if filename_postfix else os.path.splitext(config_path)[1] mode = mode if mode and mode in ['a', 'w'] else 'a'
config_data = globals().get('write_config_%s' % postfix_func_dict.get(filename_postfix, default_filename_postfix)) \ (config_path, config_data, mode)
logging.info("读取配置文件[%s]成功,配置信息[%s]", config_path, config_data)
def write_config_yaml(config_path, config_data, mode): u""" 写入配置文件
:param str config_path: 配置文件 :param dict config_data: 配置字典 :param str mode: 数据时 追加写入还是覆盖等 a w """ fw = open(config_path, mode) yaml.dump(config_data, fw) return config_data
def write_config_ini(config_path, config_data, mode): u""" 写入配置文件
:param str config_path: 配置文件 :param dict config_data: 配置字典 :param str mode: 数据时 追加写入还是覆盖等 a w """
config = ConfigParser.ConfigParser() if not os.path.exists(config_path): new_config_dic = config_data else: new_config_dic = read_config(config_path) if mode == 'a': new_config_dic.update(config_data)
for section, section_vals in config_data.items(): config.add_section(section) for key, val in section_vals.items(): config.set(section, key, val) config.write(open(config_path, "w")) logging.info("写入配置文件[%s]完成", config_path) return config_data
if __name__ == '__main__': config_path = "test.yaml" config_path = "/home/fdm/software/hugegraph/hugegraph-0.9.2/conf/gremlin-server.yaml" config_data = read_config(config_path) write_config('test2.yaml', config_data=config_data, mode='a') exit()
config_path = "config.ini" config_data = { 'sectionA': {'a': 'b', 'key1': 123} } write_config('config2.ini', config_data=config_data, mode='a') read_config(config_path)
|