13.2. ConfigParser —配置文件解析器

Note

ConfigParser模块在 Python 3 中已重命名为configparser2to3工具在将源转换为 Python 3 时将自动适应导入。

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

Note

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

See also

  • Module shlex

  • 支持创建类似 Unix Shell 的迷你语言,可用作应用程序配置文件的替代格式。

  • Module json

  • json 模块实现了 JavaScript 语法的子集,也可以用于此目的。

配置文件由以[section]头开头,后跟name: value条目开头的部分组成,并以 RFC 822样式 continue(请参见第 3.1.1 节“长头字段”); name=value也被接受。请注意,前导空格已从值中删除。可选值可以包含引用同一节中其他值的格式字符串,也可以包含特殊DEFAULT节中的值。可以在初始化和检索时提供其他默认值。以'#'';'开头的行将被忽略,可用于提供 Comments。

配置文件可能包含 Comments,并以特定字符(#;)为前缀。Comments 可以自己出现在否则为空的行中,也可以 Importing 包含值或节名称的行中。在后一种情况下,必须在其前面加上一个空白字符以将其识别为 Comments。 (为了向后兼容,只有;开始内联 Comments,而#没有.)

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

For example:

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

会将%(dir)s解析为dir的值(在这种情况下为frob)。所有参考扩展均按需完成。

可以pass将默认值作为字典传递到ConfigParser构造函数来指定默认值。可能会将其他默认值传递到get()方法中,该方法将覆盖所有其他默认值。

节通常存储在内置词典中。可以将其他字典类型传递给ConfigParser构造函数。例如,如果传递的字典类型对其键进行排序,则这些部分将在回写时进行排序,每个部分中的键也会一样。

此类不支持魔术插值行为。

所有选项名称都passoptionxform()方法传递。其默认实现将选项名称转换为小写。

2.3 版的新Function。

在 2.6 版中进行了更改:添加了* dict_type *。

在 2.7 版中更改:默认* dict_type *为collections.OrderedDict。 * allow_no_value *已添加。

插值中使用的所有选项名称都将passoptionxform()方法传递,就像其他任何选项名称引用一样。使用optionxform()的默认实现,值foo %(bar)sfoo %(BAR)s是等效的。

2.3 版的新Function。

在 2.6 版中进行了更改:添加了* dict_type *。

在 2.7 版中更改:默认* dict_type *为collections.OrderedDict。 * allow_no_value *已添加。

2.3 版的新Function。

在 2.6 版中进行了更改:添加了* dict_type *。

在 2.7 版中更改:默认* dict_type *为collections.OrderedDict。 * allow_no_value *已添加。

2.3 版的新Function。

2.3 版的新Function。

See also

  • Module shlex

  • 支持创建类似 Unix Shell 的微型语言,这些语言可用作应用程序配置文件的替代格式。

13.2.1. RawConfigParser 对象

RawConfigParser个实例具有以下方法:

1.6 版中的新Function。

import ConfigParser, os

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

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

1.6 版中的新Function。

1.6 版中的新Function。

1.6 版中的新Function。

您不一定需要使用 ConfigParser 子类来使用此方法,也可以在实例上将其重新设置为带有字符串参数的函数。例如,将其设置为str会使选项名称区分大小写:

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

请注意,在读取配置文件时,在调用optionxform()之前会删除选项名称周围的空格。

13.2.2. ConfigParser 对象

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

除非* raw *参数为 true,否则所有'%'插值都将在返回值中扩展。以与该选项相同的方式查找插值键的值。

2.3 版的新Function。

13.2.3. SafeConfigParser 对象

SafeConfigParser类实现与ConfigParser相同的扩展接口,并增加以下内容:

2.4 版的新Function。

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!"

下面的Functionopt_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'
首页