Python的配置文件(configparser)不接受没有值的键。

21

我正在编写一个脚本,从配置文件中读取数据,并且想要像configparser的设计方式一样使用它,具体信息在这里阐述:http://docs.python.org/release/3.2.1/library/configparser.html

我正在使用Python 3.2.1。当脚本完成后,它将在运行Windows 2008 R2操作系统的机器上使用相同版本或者兼容的最新版本的Python。

#!/user/bin/env python
import configparser

config = configparser.ConfigParser()
config.read('c:\exclude.ini')
config.sections()

读取exclude.ini文件没问题了,但是如果我有一个没有键的值,就会出错。考虑自己哪里出错了,我试着解析这里列出的示例: http://docs.python.org/release/3.2.1/library/configparser.html#supported-ini-file-structure

每次它仍然会抛出以下错误:

File "C:\Python32\lib\configparser.py", line 1081, in _read
    raise e
configparser.ParsingError: Source contains parsing errors: c:\exclude.ini
    [line 20]: 'key_without_value\n'

我很无助......我正在字面上复制/粘贴来自文档的示例代码,而且它不像应该那样工作。我只能假设我错过了某些东西,因为我也找不到有类似问题的人。

2个回答

32

ConfigParser构造函数有一个关键字参数allow_no_value,默认值为False

尝试将其设置为true,我敢打赌它会对你有用。


1
非常好,谢谢Karl。也许我应该给他们写一封信,建议将他们的示例.ini更改为在该部分上方放置注释,指出只有在更改构造函数时该部分才起作用。我想我应该阅读整个文档,但是按照设置的方式,它看起来应该默认情况下就像这样工作。 - Sparc
即使该部分看起来像这样,也可以正常工作:[软件] 3700 Journal Copy 1.0.2 Adobe Flash Player 11 ActiveX Adobe Reader X (10.1.7) - 德语 DotNet Framework 4.0 [...] - enthus1ast
要了解更多 configparser 的最新功能,请查看最新的 Python 3 文档allow_no_value 仍然可用。OP 指定使用的是 Python 3.2.1 版本。 - DanielTuzes

1
class RawConfigParser:
def __init__(self, defaults=None, dict_type=_default_dict,
             allow_no_value=False):
    self._dict = dict_type
    self._sections = self._dict()
    self._defaults = self._dict()
    if allow_no_value:
        self._optcre = self.OPTCRE_NV
    else:
        self._optcre = self.OPTCRE
    if defaults:
        for key, value in defaults.items():
            self._defaults[self.optionxform(key)] = value

导入 ConfigParser 模块

cf = ConfigParser.ConfigParser(allow_no_value=True)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接