13.2. ConfigParser配置文件解析器

在Python 3中,ConfigParser模块已重命名为configparser 2to3 之内工具将会自动地适应进口将源文件转换为 Python 3 时。

本模块定义了类ConfigParserConfigParser类实现了一个基本的配置文件解析器语言,它提供了类似于在Microsoft Windows INI文件中的结构。您可以使用它来编写可由终端用户轻松定制的Python程序。

此库并解释或写入 Windows 注册表扩展版的 INI 语法中使用的值类型前缀。

请参见

Module shlex
Support for a creating Unix shell-like mini-languages which can be used as an alternate format for application configuration files.
Module json
The json module implements a subset of JavaScript syntax which can also be used for this purpose.

配置文件包含由[section]标题引导的部分,后面是名称: 条目,继续使用 RFC 822的风格(参看 3.1.1,"长标题域"一节);name = value也可以接受。请注意,前导空格将从值中删除。可选的值可以包含引用其他同一节中的值或值在一种特殊的默认节中的格式字符串。初始化和检索,可以提供额外的默认值。'#'';'开头的行被忽略,并可能用来提供意见。

配置文件可能包含注释,以特定的字符 (#;) 作为前缀。评论可能会出现自己在另外的空的行中,或者可能在持有值或节名称的行中输入。在后者的情况下,他们需要之前由一个空格字符被视为注释。(为向后兼容性,只有;开始内联注释,而#则不能)

在核心功能, SafeConfigParser支持插值。这意味着值可以包含引用其他同一节中的值或值在一种特殊的默认节中的格式字符串。在初始化,可以提供额外的默认值。

举个例子:

[My Section]
foodir: %(dir)s/whatever
dir=frob
long: this value continues
   in the next line

将解析%(dir) sdir (在本例中简称 frob ) 的值。所有引用扩展都进行了需求。

可以通过将它们传递到一本字典作为ConfigParser构造函数指定默认值。更多违约可能传入将覆盖所有其他的get ()方法。

部分通常存储在内置的字典中。一种替代的字典类型可以传递给ConfigParser的构造函数。例如,如果字典类型通过对它的键进行排序,各节将排序对回写式,将每个部分中的注册表项。

class ConfigParser.RawConfigParser([defaults[, dict_type[, allow_no_value]]])

基本配置对象中。当给定了默认值时,它被初始化到内在的默认值的字典。当给出了dict_type时,它将用于创建字典对象章节列表,在某一节的选项和默认值。allow_no_value是真的 (默认:),选项不接受值 ;提出了一种为这些值是None

此类不支持神奇插值的行为。

所有选项名称被都通过optionxform()方法。其默认实现将选项名称转换为小写字母。

新版本 2.3。

2.6 版本中的更改:添加了dict_type

2.7 版本中的更改:默认dict_type收藏。OrderedDict。添加了allow_no_value

class ConfigParser.ConfigParser([defaults[, dict_type[, allow_no_value]]])

RawConfigParser实现神奇的插补功能并将可选参数添加到get ()items()方法的派生的类。的默认值的值必须是适当的%() 的字符串插值。请注意, __name__是内在的默认值 ;其值是该节的名称,并且将覆盖任何默认设置中提供的值。

在插值中使用的所有选项名称将都通过optionxform()方法就像任何其他选项的名称引用。使用optionxform()的默认实现,值foo %(bar) s美孚 %(酒吧) s是等效的。

新版本 2.3。

2.6 版本中的更改:添加了dict_type

2.7 版本中的更改:默认dict_type收藏。OrderedDict。添加了allow_no_value

class ConfigParser.SafeConfigParser([defaults[, dict_type[, allow_no_value]]])

ConfigParser实现的神奇的插补功能更理智 variant 类型的派生的类。此实现也在更可预测。新的应用程序应该更喜欢这个版本,如果他们不想要的 Python 的旧版本兼容。

新版本 2.3。

2.6 版本中的更改:添加了dict_type

2.7 版本中的更改:默认dict_type收藏。OrderedDict。添加了allow_no_value

exception ConfigParser.Error

对于其他 configparser 的所有异常的基类。

exception ConfigParser.NoSectionError

找不到指定的一段时引发的异常。

exception ConfigParser.DuplicateSectionError

如果add_section()用已存在的节的名称调用将引发的异常。

exception ConfigParser.NoOptionError

指定的节中找不到指定的选项时引发的异常。

exception ConfigParser.InterpolationError

当出现执行字符串插值问题时引发的异常的基类。

exception ConfigParser.InterpolationDepthError

不能完成字符串插值,因为迭代次数超过MAX_INTERPOLATION_DEPTH时引发的异常。 InterpolationError的子类。

exception ConfigParser.InterpolationMissingOptionError

当从一个值引用选项时引发的异常不存在。 InterpolationError的子类。

新版本 2.3。

exception ConfigParser.InterpolationSyntaxError

在其中进行替换的源文本不符合所需的语法时引发的异常。 InterpolationError的子类。

新版本 2.3。

exception ConfigParser.MissingSectionHeaderError

试图解析文件已没有节标头时引发的异常。

exception ConfigParser.ParsingError

试图解析文件发生错误时引发的异常。

ConfigParser.MAX_INTERPOLATION_DEPTH

最大深度为递归插值的get ()原始参数为 false。这是仅对ConfigParser类别有关。

请参见

Module shlex
Support for a creating Unix shell-like mini-languages which can be used as an alternate format for application configuration files.

13.2.1. RawConfigParser Objects

RawConfigParser实例具有以下方法:

RawConfigParser.defaults()

返回一个包含实例范围的默认值的字典。

RawConfigParser.sections()

返回一个列表部分可用 ;默认值不是包括在列表中。

RawConfigParser.add_section(section)

添加命名实例一一节。如果已经存在具有给定名称的一段,被引发DuplicateSectionError 如果传递一种新的默认值的名称 (或任何不区分大小写的变种),则会引发ValueError

RawConfigParser.has_section(section)

指示是否命名的节是目前在配置中。不承认是默认部分中。

RawConfigParser.options(section)

返回指定中的可用选项的列表。

RawConfigParser.has_option(section, option)

如果给定的区域存在,并且包含给定的选项,返回True否则返回False

新的版本 1.6。

RawConfigParser.read(filenames)

尝试读取和解析文件名列表,返回的都成功地被解析的文件名列表。如果文件名是一个字符串或 Unicode 字符串,它被视为是一个文件名。如果无法打开文件名中名为的文件,该文件将被忽略。这样设计被为了使您可以指定潜在的配置文件位置 (例如,当前目录,用户的主目录和一些全系统目录) 的列表和列表中的所有现有配置文件将被读取。如果没有指定的文件存在, ConfigParser实例将包含一个空的数据集。需要初始的值要从文件加载的应用程序应加载所需的一个或多个调用read ()的任何可选的文件之前,请使用readfp()文件:

import ConfigParser, os

config = ConfigParser.ConfigParser()
config.readfp(open('defaults.cfg'))
config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')])

2.4 版本中的更改:返回成功解析文件名的列表。

RawConfigParser.readfp(fp[, filename])

读取和解析配置数据从文件或文件类似物体在fp (只有readline ()方法使用)。如果省略文件名fp具有name属性,这用于文件名默认值是<???>.

RawConfigParser.get(section, option)

获取命名选项值。

RawConfigParser.getint(section, option)

一种将强制选项中指定的为整数的方便方法。

RawConfigParser.getfloat(section, option)

一个便利方法,将强制选项中指定的为浮点数。

RawConfigParser.getboolean(section, option)

A convenience method which coerces the option in the specified section to a Boolean value.Note that the accepted values for the option are "1", "yes", "true", and "on", which cause this method to return True, and "0", "no", "false", and "off", which cause it to return False. These string values are checked in a case-insensitive manner. Any other value will cause it to raise ValueError.

RawConfigParser.items(section)

返回的列表(名称, 值)对给定的一节中每个选项。

RawConfigParser.set(section, option, value)

如果给定的节仍将存在,将给定的选项设置为指定的值 ;以其它方式筹集NoSectionError虽然也可以使用RawConfigParser (或ConfigParser原始参数设置为 true) 为非字符串值的内部存储,全部功能 (包括插值和输出到文件) 才能使用字符串值。

新的版本 1.6。

RawConfigParser.write(fileobject)

一个表示配置写入指定的文件对象。这种表示方法可以通过未来read ()调用来解析。

新的版本 1.6。

RawConfigParser.remove_option(section, option)

从指定的中删除指定的选项如果该节不存在),提高NoSectionError如果该选项存在要移除,返回True否则返回False

新的版本 1.6。

RawConfigParser.remove_section(section)

从配置中删除指定的部分如果部分实际上存在,返回True否则返回False

RawConfigParser.optionxform(option)

转换选项名称选项在输入文件中找到或作为通过在客户端代码应该用于内部结构的形式。默认实现返回一个小写版本的选项子类可以重写此或客户端代码可以在影响这种行为的实例上设置此名称的属性。

你不需要子类化的 ConfigParser,使用此方法,您还可以重新设置它的实例,采用一个字符串作为参数的函数上。将其设置为str,例如,会使选项名称区分大小写:

cfgparser = ConfigParser()
...
cfgparser.optionxform = str

请注意当读取配置文件,选项名称在optionxform()之前就被剥夺了周围的空白区域调用。

13.2.2. ConfigParser Objects

ConfigParser类扩展了RawConfigParser接口,添加一些可选的参数的一些方法。

ConfigParser.get(section, option[, raw[, vars]])

获取命名选项值。如果提供了var ,它必须是一本字典。选项看在var (如果提供),一节,和在违约按此顺序。

所有'%'的内插展开的返回值,除非原始的说法不实。插值键的值是在选项相同的方式抬起头。

ConfigParser.items(section[, raw[, vars]])

返回的列表(名称, 值)对给定的一节中每个选项。可选参数具有相同的含义, get ()方法。

新版本 2.3。

13.2.3. SafeConfigParser Objects

SafeConfigParser类实现相同的扩展的接口ConfigParser,加上以下:

SafeConfigParser.set(section, option, value)

如果给定的节仍将存在,将给定的选项设置为指定的值 ;以其它方式筹集NoSectionError必须是一个字符串 (strunicode) ;如果不是,提出了TypeError

在 2.4 版本新。

13.2.4. Examples

写入配置文件示例:

import ConfigParser

config = ConfigParser.RawConfigParser()

# When adding sections or items, add them in the reverse order of
# how you want them to be displayed in the actual file.
# In addition, please note that using RawConfigParser's and the raw
# mode of ConfigParser's respective set functions, you can assign
# non-string values to keys internally, but will receive an error
# when attempting to write to a file or when you get it in non-raw
# mode. SafeConfigParser does not allow such assignments to take place.
config.add_section('Section1')
config.set('Section1', 'an_int', '15')
config.set('Section1', 'a_bool', 'true')
config.set('Section1', 'a_float', '3.1415')
config.set('Section1', 'baz', 'fun')
config.set('Section1', 'bar', 'Python')
config.set('Section1', 'foo', '%(bar)s is %(baz)s!')

# Writing our configuration file to 'example.cfg'
with open('example.cfg', 'wb') as configfile:
    config.write(configfile)

再次读取配置文件的示例:

import ConfigParser

config = ConfigParser.RawConfigParser()
config.read('example.cfg')

# getfloat() raises an exception if the value is not a float
# getint() and getboolean() also do this for their respective types
a_float = config.getfloat('Section1', 'a_float')
an_int = config.getint('Section1', 'an_int')
print a_float + an_int

# Notice that the next output does not interpolate '%(bar)s' or '%(baz)s'.
# This is because we are using a RawConfigParser().
if config.getboolean('Section1', 'a_bool'):
    print config.get('Section1', 'foo')

要得到插值,您将需要使用ConfigParserSafeConfigParser

import ConfigParser

config = ConfigParser.ConfigParser()
config.read('example.cfg')

# Set the third, optional argument of get to 1 if you wish to use raw mode.
print config.get('Section1', 'foo', 0) # -> "Python is fun!"
print config.get('Section1', 'foo', 1) # -> "%(bar)s is %(baz)s!"

# The optional fourth argument is a dict with members that will take
# precedence in interpolation.
print config.get('Section1', 'foo', 0, {'bar': 'Documentation',
                                        'baz': 'evil'})

默认设置是在所有三种类型的 ConfigParsers 中可用。如果使用一个选项不定义的其他地方,它们用于在插值。

import ConfigParser

# New instance with 'bar' and 'baz' defaulting to 'Life' and 'hard' each
config = ConfigParser.SafeConfigParser({'bar': 'Life', 'baz': 'hard'})
config.read('example.cfg')

print config.get('Section1', 'foo') # -> "Python is fun!"
config.remove_option('Section1', 'bar')
config.remove_option('Section1', 'baz')
print config.get('Section1', 'foo') # -> "Life is hard!"

下面的函数opt_move可以用于各个部分之间移动选项:

def opt_move(config, section1, section2, option):
    try:
        config.set(section2, option, config.get(section1, option, 1))
    except ConfigParser.NoSectionError:
        # Create non-existent section
        config.add_section(section2)
        opt_move(config, section1, section2, option)
    else:
        config.remove_option(section1, option)

已知某些配置文件包括设置没有价值,但是,否则为符合由ConfigParser支持的语法。Allow_no_value参数的构造函数可以用于指示应该接受这样的值:

>>> import ConfigParser
>>> import io

>>> sample_config = """
... [mysqld]
... user = mysql
... pid-file = /var/run/mysqld/mysqld.pid
... skip-external-locking
... old_passwords = 1
... skip-bdb
... skip-innodb
... """
>>> config = ConfigParser.RawConfigParser(allow_no_value=True)
>>> config.readfp(io.BytesIO(sample_config))

>>> # Settings with values are treated as before:
>>> config.get("mysqld", "user")
'mysql'

>>> # Settings without values provide None:
>>> config.get("mysqld", "skip-bdb")

>>> # Settings which aren't specified still raise an error:
>>> config.get("mysqld", "does-not-exist")
Traceback (most recent call last):
  ...
ConfigParser.NoOptionError: No option 'does-not-exist' in section: 'mysqld'