当部分 header 本身有一个 ] 时,ConfigParser 中断

ConfigParser breaking when section header itself has an ]

我正在这样使用 ConfigParser 模块:

from ConfigParser import ConfigParser
c = ConfigParser()
c.read("pymzq.ini")

但是,这些部分会像这样搞砸:

>>> c.sections()
['pyzmq:platform.architecture()[0']

对于 pymzq.ini 文件,其标题中有 ] 表示:

[pyzmq:platform.architecture()[0] == '64bit']
url = ${pkgserver:fullurl}/pyzmq/pyzmq-2.2.0-py2.7-linux-x86_64.egg

Looks like ConfigParser uses a regex that only parses section lines up to the first closing bracket,所以这符合预期。

您应该能够继承 ConfigParser/RawConfigParser 并将正则表达式更改为更适合您情况的内容,例如 ^\[(?P<header>.+)\]$,也许。

感谢@AKX 指点,我选择了:

class MyConfigParser(ConfigParser):
    _SECT_TMPL = r"""
        \[                                 # [
        (?P<header>[^$]+)                  # Till the end of line
        \]                                 # ]
        """
    SECTCRE = re.compile(_SECT_TMPL, re.VERBOSE)

如果您有更好的版本,请告诉我。 Source原码ConfigParser.