zoukankan      html  css  js  c++  java
  • ConfigParser导入ini配置文件关键字强制转小写解决办法

    背景

    在code中写入参数和路径等配置会导致编译后无法更改,使用配置文件可提高代码维护性。

    Python自带的configparser支持通用的ini配置文件,可以获取不同分组下的键值对。

    测试

    示范配置文件:

    #conf.ini
    
    [Path]
    Player = D:Programvlc.exe
    Editor = C:Windowssystem32
    otepad.exe
    

    随后通过Python调用并生成配置字典:

    from configparser import ConfigParser
    
    conf = ConfigParser()
    conf.read("./conf.ini")
    path = dict(conf.items("Path"))
    print(path)
    
    # Output:
    # {'player': 'D:\Program\vlc.exe', 'editor': 'C:\Windows\system32\notepad.exe'}
    

    关键字都变成了小写,无法用于case sensitive场景,如何保留原始关键字?

    优化

    通过摸排,发现是ConfigParser自带的optionxfrom()方法中含有lower()函数将字符串强制输出为小写。

    因此解决方案有两个:

    1. 修改自带的optionxfrom()方法,删掉lower()函数,更换环境失效。不推荐!

    2. 声明一个自己的解析类,继承原有ConfigParser并重写optionxfrom()方法,推荐!

    from configparser import ConfigParser
    
    class MyParser(ConfigParser):
        "Inherit from built-in class: ConfigParser"
        def optionxform(self,optionstr):
            "Rewrite without lower()"
            return optionstr
    
    conf = MyParser()
    conf.read("./conf.ini")
    path = dict(conf.items("Path"))
    print(path)
    
    # Output:
    # {'Player': 'D:\Program\vlc.exe', 'Editor': 'C:\Windows\system32\notepad.exe'}
    

    问题解决!

  • 相关阅读:
    线性代数:矩阵行列式
    线性代数:逆变换
    线性代数:线性变换
    线性代数:零空间
    线性代数:向量乘法
    线性代数基础:向量组合
    线性代基础理论:向量
    线性代基础理论:矩阵
    SpringBoot 消费NSQ消息
    将Oracle中的数据放入elasticsearch
  • 原文地址:https://www.cnblogs.com/azureology/p/13177773.html
Copyright © 2011-2022 走看看