一、实验环境
1.Windows10x64
2.anaconda4.6.9 + python3.7.1(anaconda集成,不需单独安装)
二、代码示例
# -*- coding: utf-8 -*-
import os
from configparser import ConfigParser, NoSectionError
debug = False
def debug_print(str):
if debug:
print(str)
class GetConfig(ConfigParser):
def __init__(self, defaults=None):
"""
初始化函数
:param defaults:
"""
ConfigParser.__init__(self, defaults=None)
def optionxform(self, optionstr):
"""
解决ConfigParser将键值对强制转换为小写问题
:param optionstr:
:return:
"""
return optionstr
def open_file(self, file_name):
"""
打开config文件夹
:param file_name: config文件路径
:return:
"""
if os.path.exists(file_name):
debug_print('%s exists' % (file_name))
self.read(file_name)
return True
else:
debug_print('%s do not exists' % (file_name))
return False
def get_sections(self):
"""
获取config中所有section
:return: section列表
"""
section = self.sections()
debug_print(section)
return section
def check_section(self, *args, **kwargs):
def check_section_type(*args, **kwargs):
if isinstance(args[0], str):
print('The first parameter (section) must be a string')
return
return check_section_type
@check_section
def get_options(self, section):
"""
返回section中所有option
:param section: 指定section
:return: option列表
"""
try:
options_list = self.options(section)
return options_list
except NoSectionError as e:
debug_print(e)
return
@check_section
def get_dicts(self, section):
"""
返回section中键值对
:param section: 指定section
:return: 键值对
"""
try:
list_str = self.items(section)
dict_str = dict(list_str)
return dict_str
except NoSectionError as e:
debug_print(e)
return
@check_section
def get_options_match_str(self, section, match_str):
"""
使用指定字符串匹配option列表
:param section: 指定section
:param match_str: 需要匹配的字符串
:return: 匹配列表
"""
options_list = self.get_options(section)
match_list = []
for each in options_list:
if match_str in each:
match_list.append(each)
return match_list
@check_section
def get_para(self, section, key):
"""
使用section和key索引value
:param section: 指定section
:param key: 指定key
:return: 索引值
"""
dicts = self.get_dicts(section)
if dicts:
result = dicts.get(key, None)
return result
else:
return
if __name__ == '__main__':
debug = True
config = GetConfig()
config.open_file(r'g:gejunpingextract_binToolconfig_block.cfg')
sections = config.get_sections()
ret = config.get_para('AM620', 'AM620_128G')
print(ret)
options = config.get_options('AM620')
print(options)
match_list = config.get_options_match_str('AM620', 'PREFIX')
print(match_list)
for each_match in match_list:
print(config.get_para('AM620', each_match))
dicts = config.get_dicts('AM620')
print(dicts)