Py学习  »  Python

配置分析器。Python2.7[副本]

Samvel • 5 年前 • 1535 次点击  

我发现了一个有趣的发现。 我写了一个配置文件读取程序,

import ConfigParser
class  ConfReader(object):
    ConfMap = dict()

    def __init__(self):
        self.config = ConfigParser.ConfigParser()
        self.config.read('./Config.ini')
        self.__loadConfigMap()

    def __loadConfigMap(self):
        for sec in self.config.sections():
            for key,value in self.config.items(sec):
                print 'key = ', key, 'Value = ', value
                keyDict = str(sec) + '_' + str(key)
                print 'keyDict = ' + keyDict  
                self.ConfMap[keyDict] = value

    def getValue(self, key):
        value = ''
        try:
            print ' Key = ', key
            value = self.ConfMap[key] 
        except KeyError as KE:
            print 'Key', KE , ' didn\'t found in configuration.'
    return value

class MyConfReader(object):
    objConfReader = ConfReader()

def main():
     print MyConfReader().objConfReader.getValue('DB2.poolsize')
     print MyConfReader().objConfReader.getValue('DB_NAME')

if __name__=='__main__':
    main()

我的config.ini文件看起来像,

[DB]
HOST_NAME=localhost
NAME=temp
USER_NAME=postgres
PASSWORD=mandy

loadconfigmap()工作正常。但在读取键和值时,它会使键的大小写变小。我不明白原因。有人能解释一下为什么是这样吗?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/43362
 
1535 次点击  
文章 [ 1 ]  |  最新文章 5 年前
Martijn Pieters
Reply   •   1 楼
Martijn Pieters    11 年前

ConfigParser.ConfigParser() ConfigParser.RawConfigParser() ,其行为记录如下:

所有选项名称都通过 optionxform() 方法。它的默认实现将选项名转换为小写。

这是因为这个模块解析的是windows ini文件,而这些文件应该是不区分大小写的。

您可以通过替换 RawConfigParser.optionxform() function :

self.config = ConfigParser.ConfigParser()
self.config.optionxform = str

str 不加更改地传递选项。