python - ConfigParser 中不区分大小写的部分

标签 python configparser

我正在看Python 3.6 documentation它说的地方

By default, section names are case sensitive but keys are not [1].

对于脚注,它说

[1] (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) Config parsers allow for heavy customization. If you are interested in changing the behaviour outlined by the footnote reference, consult the Customizing Parser Behaviour section.

所以我查看“14.2.7.自定义解析器行为”,但我找不到如何使部分不区分大小写的描述。

我想要这样的部分:

[SETTINGS]
...

可以像这样config['section']进行访问,但目前我收到错误。这是我想要应用的配置解析器的唯一更改。

最佳答案

您可以在 Python 3.x 中相当轻松地完成此操作,方法是将某些内容作为 ConfigParser documentation 中描述的可选 dict_type= 关键字参数传递。 - 在本例中,我们希望类型是不区分大小写的有序字典

不幸的是,标准库中没有一个,也没有我所知道的圆锥形实现......所以我拼凑了一个作为示例。它尚未经过严格测试,但足以说明总体思路。

注意:为了进行测试,我使用了以下 simple.ini 文件(我从 pymotw 中获取):

# This is a simple example with comments.
[bug_tracker]
url = http://localhost:8080/bugs/
username = dhellmann
; You should not store passwords in plain text
; configuration files.
password = SECRET

这是一个演示,展示了如何使用它来完成所需的操作:

import collections
from configparser import ConfigParser

class CaseInsensitiveDict(collections.MutableMapping):
    """ Ordered case insensitive mutable mapping class. """
    def __init__(self, *args, **kwargs):
        self._d = collections.OrderedDict(*args, **kwargs)
        self._convert_keys()
    def _convert_keys(self):
        for k in list(self._d.keys()):
            v = self._d.pop(k)
            self._d.__setitem__(k, v)
    def __len__(self):
        return len(self._d)
    def __iter__(self):
        return iter(self._d)
    def __setitem__(self, k, v):
        self._d[k.lower()] = v
    def __getitem__(self, k):
        return self._d[k.lower()]
    def __delitem__(self, k):
        del self._d[k.lower()]


parser = ConfigParser(dict_type=CaseInsensitiveDict)
parser.read('simple.ini')

print(parser.get('bug_tracker', 'url'))  # -> http://localhost:8080/bugs/
print(parser.get('Bug_tracker', 'url'))  # -> http://localhost:8080/bugs/

关于python - ConfigParser 中不区分大小写的部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49755480/

相关文章:

python - 类型错误 : get() missing 1 required positional argument: 'index1'

python-2.7 - 在Python 2.7中手动构建ConfigParser的深拷贝

python - 扩展插值在 configparser 中不起作用

python - 用坐标绘制 NetworkX Graph

coding-style - 在 Python 中创建常量的约定

python - 从 Dataflow python 作业写入 bigquery 中的分区表

python - Pyspark - Python3 使用 configparser 从文件中获取变量

java - 从套接字服务器发送 2 个图像

gcloud - gsutil ConfigParser.ParsingError : File contains parsing errors

python - 当 header 不在文件开头时是否可以使用 ConfigParser?