On this page
13.2. ConfigParser —配置文件解析器
Note
ConfigParser模块在 Python 3 中已重命名为configparser
。2to3工具在将源转换为 Python 3 时将自动适应导入。
此模块定义类ConfigParser。 ConfigParser类实现了基本的配置文件解析器语言,该语言提供的结构类似于您在 Microsoft Windows INI 文件中找到的结构。您可以使用它来编写可由finally用户轻松定制的 Python 程序。
Note
该库不解释或写入 INI 语法的 Windows 注册表扩展版本中使用的值类型前缀。
See also
配置文件由以[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构造函数。例如,如果传递的字典类型对其键进行排序,则这些部分将在回写时进行排序,每个部分中的键也会一样。
-
- class *
ConfigParser.
RawConfigParser
([默认值[[, dict_type * [,* allow_no_value *]]])
- 基本配置对象。当给出* defaults 时,它被初始化为固有默认字典。给出 dict_type 时,它将用于为节列表,节中的选项以及默认值创建字典对象。当 allow_no_value *为 true(默认值:
False
)时,接受不带值的选项;否则为 false。这些显示的值为None
。
- class *
此类不支持魔术插值行为。
所有选项名称都passoptionxform()方法传递。其默认实现将选项名称转换为小写。
2.3 版的新Function。
在 2.6 版中进行了更改:添加了* dict_type *。
在 2.7 版中更改:默认* dict_type *为collections.OrderedDict。 * allow_no_value *已添加。
-
- class *
ConfigParser.
ConfigParser
([默认值[[, dict_type * [,* allow_no_value *]]])
- RawConfigParser的派生类实现了神奇的插值Function,并向get()和items()方法添加了可选参数。 * defaults 中的值必须适合
%()s
字符串插值。注意 __ name __ 是固有的默认值;它的值是节名,它将覆盖 defaults *中提供的任何值。
- class *
插值中使用的所有选项名称都将passoptionxform()
方法传递,就像其他任何选项名称引用一样。使用optionxform()
的默认实现,值foo %(bar)s
和foo %(BAR)s
是等效的。
2.3 版的新Function。
在 2.6 版中进行了更改:添加了* dict_type *。
在 2.7 版中更改:默认* dict_type *为collections.OrderedDict。 * allow_no_value *已添加。
-
- class *
ConfigParser.
SafeConfigParser
([默认值[[, dict_type * [,* allow_no_value *]]])
- ConfigParser的派生类实现了魔术插值Function的更健全的变体。此实现也更可预测。如果新应用程序不需要与旧版本的 Python 兼容,则应首选此版本。
- class *
2.3 版的新Function。
在 2.6 版中进行了更改:添加了* dict_type *。
在 2.7 版中更改:默认* dict_type *为collections.OrderedDict。 * allow_no_value *已添加。
exception
ConfigParser.
Error
- 所有其他 configparser 异常的 Base Class。
exception
ConfigParser.
NoSectionError
- 未找到指定节时引发异常。
exception
ConfigParser.
DuplicateSectionError
- 如果使用已存在的节的名称调用
add_section()
,则会引发异常。
- 如果使用已存在的节的名称调用
exception
ConfigParser.
NoOptionError
- 在指定的部分中找不到指定的选项时引发异常。
exception
ConfigParser.
InterpolationError
- 在执行字符串插值时发生问题时引发的异常的 Base Class。
exception
ConfigParser.
InterpolationDepthError
- 当由于迭代次数超过MAX_INTERPOLATION_DEPTH而无法完成字符串插值时引发异常。 InterpolationError的子类。
exception
ConfigParser.
InterpolationMissingOptionError
- 从值引用的选项不存在时引发的异常。 InterpolationError的子类。
2.3 版的新Function。
- exception
ConfigParser.
InterpolationSyntaxError
- 当进行替换的源文本不符合要求的语法时,引发异常。 InterpolationError的子类。
2.3 版的新Function。
exception
ConfigParser.
MissingSectionHeaderError
- try分析没有节头的文件时引发异常。
exception
ConfigParser.
ParsingError
- try解析文件时发生错误时引发异常。
ConfigParser.
MAX_INTERPOLATION_DEPTH
- 当* raw *参数为 false 时,
get()
的递归插值的最大深度。这仅与ConfigParser类有关。
- 当* raw *参数为 false 时,
See also
Module shlex
支持创建类似 Unix Shell 的微型语言,这些语言可用作应用程序配置文件的替代格式。
13.2.1. RawConfigParser 对象
RawConfigParser个实例具有以下方法:
RawConfigParser.
defaults
( )- 返回包含实例范围默认值的字典。
RawConfigParser.
sections
( )- 返回可用部分的列表;
DEFAULT
不包括在列表中。
- 返回可用部分的列表;
RawConfigParser.
add_section
(* section *)- 将名为* section *的部分添加到实例。如果已经存在具有给定名称的部分,则会引发DuplicateSectionError。如果传递了名称
DEFAULT
(或任何不区分大小写的变体),则会引发ValueError。
- 将名为* section *的部分添加到实例。如果已经存在具有给定名称的部分,则会引发DuplicateSectionError。如果传递了名称
RawConfigParser.
has_section
(* section *)- 指示配置中是否存在命名部分。
DEFAULT
部分未得到确认。
- 指示配置中是否存在命名部分。
RawConfigParser.
options
(* section *)- 返回指定* section *中可用选项的列表。
RawConfigParser.
has_option
(* section , option *)
1.6 版中的新Function。
RawConfigParser.
read
(文件名)- try读取和解析文件名列表,返回成功解析的文件名列表。如果* filenames 是字符串或 Unicode 字符串,则将其视为单个文件名。如果无法打开以 filenames *命名的文件,则该文件将被忽略。pass设计,您可以指定潜在配置文件位置的列表(例如,当前目录,用户的主目录和某些系统范围的目录),并且将读取列表中的所有现有配置文件。如果不存在任何命名文件,则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 * [,文件名])- 从* fp 中的文件或类似文件的对象读取和解析配置数据(仅使用readline()方法)。如果Ellipsis filename 且 fp 具有
name
属性,该属性用于 filename *;默认值为<???>
。
- 从* fp 中的文件或类似文件的对象读取和解析配置数据(仅使用readline()方法)。如果Ellipsis filename 且 fp 具有
RawConfigParser.
get
(* section , option *)- 获取名为* section 的 option *值。
RawConfigParser.
getint
(* section , option *)- 一种便利方法,将指定* section 中的 option *强制为整数。
RawConfigParser.
getfloat
(* section , option *)- 一种便利方法,将指定* section 中的 option *强制为浮点数。
RawConfigParser.
getboolean
(* section , option *)- 一种便利方法,用于将指定* section 中的 option *强制为布尔值。请注意,该选项的可接受值为
"1"
,"yes"
,"true"
和"on"
,这将导致此方法返回True
,以及"0"
,"no"
,"false"
和"off"
导致其返回False
。这些字符串值以不区分大小写的方式检查。任何其他值将导致它提高ValueError。
- 一种便利方法,用于将指定* section 中的 option *强制为布尔值。请注意,该选项的可接受值为
RawConfigParser.
items
(* section *)- 返回给定* section *中每个选项的
(name, value)
对列表。
- 返回给定* section *中每个选项的
RawConfigParser.
set
(* section , option , value *)- 如果给定的部分存在,则将给定的选项设置为指定的值;否则加NoSectionError。虽然可以将RawConfigParser(或将_raw 参数设置为 true 的ConfigParser)用于内部存储非字符串值,但只能使用字符串值才能实现全部Function(包括内插和输出到文件)。
1.6 版中的新Function。
RawConfigParser.
write
(* fileobject *)- 将配置的表示形式写入指定的文件对象。将来的read()调用可以解析此表示形式。
1.6 版中的新Function。
RawConfigParser.
remove_option
(* section , option *)- 从指定的* section 中删除指定的 option *。如果该部分不存在,请引发NoSectionError。如果该选项已存在,则返回True;否则返回False。
1.6 版中的新Function。
RawConfigParser.
remove_section
(* section *)- 从配置中删除指定的* section *。如果该部分实际上存在,则返回
True
。否则返回False
。
- 从配置中删除指定的* section *。如果该部分实际上存在,则返回
RawConfigParser.
optionxform
(* option *)- 将在 Importing 文件中找到的或由 Client 端代码传递的选项名称* option 转换为应在内部结构中使用的形式。默认实现返回 option *的小写版本;子类可以覆盖此属性,或者 Client 端代码可以在实例上设置此名称的属性以影响此行为。
您不一定需要使用 ConfigParser 子类来使用此方法,也可以在实例上将其重新设置为带有字符串参数的函数。例如,将其设置为str
会使选项名称区分大小写:
cfgparser = ConfigParser()
...
cfgparser.optionxform = str
请注意,在读取配置文件时,在调用optionxform()之前会删除选项名称周围的空格。
13.2.2. ConfigParser 对象
ConfigParser类扩展了RawConfigParser接口的某些方法,并添加了一些可选参数。
ConfigParser.
get
(* section , option * [,* raw * [,* vars *]])- 获取名为* section 的 option 值。如果提供了 vars ,则它必须是字典。在 vars (如果提供), section 和 defaults 中按该 Sequences 查找 option *。
除非* raw *参数为 true,否则所有'%'
插值都将在返回值中扩展。以与该选项相同的方式查找插值键的值。
ConfigParser.
items
(* section * [,* raw * [,* vars *]])- 返回给定* section *中每个选项的
(name, value)
对列表。可选参数的含义与get()方法的含义相同。
- 返回给定* section *中每个选项的
2.3 版的新Function。
13.2.3. SafeConfigParser 对象
SafeConfigParser类实现与ConfigParser相同的扩展接口,并增加以下内容:
SafeConfigParser.
set
(* section , option , value *)- 如果给定的部分存在,则将给定的选项设置为指定的值;否则加NoSectionError。 * value *必须是字符串(str或unicode);如果不是,则引发TypeError。
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')
要进行插值,您将需要使用ConfigParser或SafeConfigParser:
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'