python–工具–ini处理
# -*- coding: utf-8 -*-
"""
author:drliu
date:2022/3/18
desc: 该文件用于
sample:
获取INI配置文件内容
_config = parse_ini(_path)
使用现有的字典去修改INI
modify_ini(_file_path, _config_dict)
"""
# -----------------------------------------------------------------------------------------------------------
# 调用系统库,三方库
# -----------------------------------------------------------------------------------------------------------
import os
import sys
import re
import random
from ConfigParser import ConfigParser
from lib.print_log import print_log
from lib.global_args import *
# -----------------------------------------------------------------------------------------------------------
# 私有参数配置
# -----------------------------------------------------------------------------------------------------------
_current_file = os.path.abspath(__file__)
_current_dir = os.path.dirname(_current_file)
def replace_notes(file_path, old_list, new_list):
"""定义修改 # 号的函数,这么做的目的是为了使在使用ConfigParser的set时不把注释行去掉"""
with open(file_path, 'r+') as fopen:
w_str = ""
for line in fopen:
if re.search(old_list, line):
# str(random.random()):随机的0-1的小数并转换为字符串
line = re.sub(old_list, str(random.random()) + new_list, line)
w_str += line
else:
w_str += line
with open(file_path, 'w+') as wopen:
wopen.write(w_str)
def recover_notes(file_path, old_list, new_list):
"""定义将 # 号修改回来的函数"""
with open(file_path, 'r+') as fopen:
w_str = ""
for line in fopen:
if re.search(old_list, line):
line = re.sub(old_list, new_list, line)
w_str += line
else:
w_str += line
with open(file_path, 'w+') as wopen:
wopen.write(w_str)
def modify_ini(file_path, config_dict):
"""
modify target ini file based on input config_dict
:param file_path:
:param config_dict:
:return:
"""
try:
if not os.path.exists(file_path):
raise Exception('file:{0} not exists, please check '.format(file_path))
# 修改带有#号的注释
replace_notes(file_path, '#', '^.*aba11注释03aba = ')
parser = ConfigParser()
parser.read(file_path)
if set(config_dict.keys()) > set(parser.sections()):
raise Exception(
'sections:{0} get from session memory not match file:{1} section :{2}'.format(config_dict.keys(), file_path,
parser.sections()))
for section, section_values in config_dict.items():
for key, value in section_values.items():
parser.set(section, key, value)
with open(file_path, "w+") as f:
parser.write(f)
# 将注释还原
recover_notes(file_path, '^.*aba11注释03aba = ', '#', )
except Exception as err:
raise Exception(err)
def parse_ini(file_path):
"""
:param file_path:
:aim parse all key,sections in target ini
:param file_name: /home/config/config.ini
:return: {'INSIGHT': {'a': 'AA'}, 'GENERAL': {'time_interval': '30', 'target_path': '/home/yunwei', 'ommuser': 'zxomm', 'is_trust': '1'}}
"""
try:
if not os.path.exists(file_path):
raise Exception('file:{0} not exists, please check '.format(file_path))
parser = ConfigParser()
parser.read(file_path)
sections = parser.sections()
_config = {}
for item in sections:
key_list = parser.options(item)
_config[item] = {}
for key in key_list:
_config[item][key] = parser.get(item, key)
return _config
except Exception as err:
raise Exception(err)
def main():
"""代码示例
获取INI配置文件内容
_config = parse_ini(_path)
使用现有的字典去修改INI
modify_ini(_file_path, _config_dict)
"""
pass
if __name__ == '__main__':
_config = parse_ini(TEST_CONFIG_FILE_PATH)
print_log('INFO', _config)
_config = {'common': {'test3': '37', }}
modify_ini(TEST_CONFIG_FILE_PATH, _config)