Python configparser不接受没有值的键

2024-04-18 06:52:49 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,我正在编写一个从配置文件中读取的脚本,我想确切地使用它,就像这里所描述的那样,configparser是如何被设计来使用的:http://docs.python.org/release/3.2.1/library/configparser.html

我正在使用Python3.2.1。脚本完成后,将使用同一版本的Python在Windows 2008 R2计算机上运行,或者假设兼容,使用当时的最新版本。

#!/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'

我不知所措。。。我正在复制/粘贴文档中的示例代码,以获得我正在使用的python版本,但它并没有正常工作。我只能假设我遗漏了什么,因为我也找不到有类似问题的人。


Tags: org版本脚本confighttp示例docsread
2条回答
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

导入配置分析器

cf=ConfigParser.ConfigParser(允许没有值=True)

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

试着把它设置成真的,我打赌它会对你有用。

相关问题 更多 >