20

所以我正在编写一个从配置文件中读取的脚本,我想准确地使用 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'

我不知所措...我实际上是从文档中复制/粘贴示例代码,以获取我正在使用的确切 python 版本,但它没有按应有的方式工作。我只能假设我错过了一些东西,因为我也找不到任何有类似问题的人。

4

2 回答 2

31

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

尝试将其设置为 true,我敢打赌它会为您工作。

于 2012-02-29T00:07:37.050 回答
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

导入配置解析器

cf = ConfigParser.ConfigParser(allow_no_value=True)

于 2016-04-05T10:26:48.763 回答