1.Windows10x64
2.anaconda4.6.9 ?python3.7.1(anaconda集成,不需單獨(dú)安裝)
# -*- coding: utf-8 -*-import osfrom configparser import ConfigParser, NoSectionErrordebug = Falsedef debug_print(str): if debug: print(str)class GetConfig(ConfigParser): def __init__(self, defaults=None): """ 初始化函數(shù) :param defaults: """ ConfigParser.__init__(self, defaults=None) def optionxform(self, optionstr): """ 解決ConfigParser將鍵值對強(qiáng)制轉(zhuǎn)換為小寫問題 :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: returnif __name__ == '__main__': debug = True config = GetConfig() config.open_file(r'g:\gejunping\extract_bin\Tool\config_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)
來源:https://www.icode9.com/content-4-605101.html
聯(lián)系客服