配置類
[Section1]
Key_AAA = Value[Section2]
AnotherKey = Value
默認情況下,ConfigParser會將ini配置文件中的KEY,轉為小寫。
重載后配置類:
- 繼承類從configparser.ConfigParser改為configparser.RawConfigParser
- 重載方法optionxform,默認它會將數據轉為小寫。直接返回不轉為小寫。
class ConfigParser(configparser.RawConfigParser):def __init__(self):super().__init__()self.read(Path(BASE_PATH).joinpath('auto-api-test.ini'), encoding='utf-8')def optionxform(self, optionstr: str) -> str:"""重載此方法,數據不轉為小寫默認情況下,這個方法會轉換每次 read, get, 或 set 操作的選項名稱。默認會將名稱轉換為小寫形式。這也意味著當一個配置文件被寫入時,所有鍵都將為小寫形式。:param optionstr::return:"""return optionstr
歷史配置類ConfigParser
:
class ConfigParser(configparser.ConfigParser):def __init__(self):super().__init__()self.read(Path(BASE_PATH).joinpath('auto-api-test.ini'), encoding='utf-8')
普通調用RawConfigParser
官方文檔:https://docs.python.org/zh-cn/3.6/library/configparser.html#configparser.ConfigParser.optionxform
def test_demo6(self):config = """[Section1]Key_AAA = Value[Section2]AnotherKey = Value"""custom = configparser.RawConfigParser()custom.optionxform = lambda option: optioncustom.read_string(config)print(custom['Section1'].keys())# ['Key']print(custom['Section2'].keys())# ['AnotherKey']# 讀取keyprint(custom.get('Section2', 'AnotherKey'))