首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

ConfigParser

注意

ConfigParser模块已被重命名为configparserPython 3. 当将源代码转换为Python 3时,2to3工具将自动适应导入。

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

注意

这个库并没有解释或写在INI语法的Windows注册表扩展版本中使用的值类型的前缀。

另请参阅

Module shlex 支持创建一个可以用作应用程序配置文件的备用格式的Unix shell-mini-languages。 Module json json模块实现了也可用于此目的的JavaScript语法子集。

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

配置文件可能包含注释,并以特定字符(#;)作为前缀。注释可以单独出现在其他空行中,也可以用包含值或部分名称的行输入。在后一种情况下,它们需要以空格字符开头,才能被识别为注释。(为了向后兼容,只;启动内嵌评论,而不#启用。)

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

例如:

代码语言:javascript
复制
[My Section]
foodir: %(dir)s/whatever
dir=frob
long: this value continues
   in the next line

将解决(在这种情况下)%(dir)s的价值。所有参考扩展都是按需完成的。dirfrob

默认值可以通过将它们ConfigParser作为字典传递给构造函数来指定。可以将其他默认值传递给get()将覆盖所有其他默认值的方法。

部分通常存储在内置的字典中。另一种字典类型可以传递给ConfigParser构造函数。例如,如果传递一个字典类型来对其键进行排序,那么这些部分将在写回时被排序,这也将是每个部分中的键。

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

基本的配置对象。当默认给出,它被初始化到内在默认的字典。当给出dict_type时,它将用于为部分列表,部分内的选项以及默认值创建字典对象。当allow_no_value为true(默认:)时False,不接受值的选项被接受; 这些值就是None

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

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

2.3版本的新功能。

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

在版本2.7中更改:默认的dict_typecollections.OrderedDictallow_no_value被添加。

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

派生类RawConfigParser实现了神奇的插值功能,并为可选参数get()items()方法添加了参数。默认值中的必须适合%()s字符串插值。请注意,___name__ 是固有的默认值; 它的值是部分名称,并将覆盖_defaults中提供的任何值

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

2.3版本的新功能。

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

在版本2.7中更改:默认的dict_typecollections.OrderedDictallow_no_value被添加。

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

派生类ConfigParser实现了神奇插值功能的更加合理的变体。这个实现也是可以预测的。如果新应用程序不需要与旧版本的Python兼容,则应该更喜欢此版本。

2.3版本的新功能。

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

在版本2.7中更改:默认的dict_typecollections.OrderedDictallow_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 支持创建一个可以用作应用程序配置文件的备用格式的Unix shell-mini-languages。

1. RawConfigParser对象

RawConfigParser 实例具有以下方法:

RawConfigParser.defaults()

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

RawConfigParser.sections()

返回可用部分的列表; DEFAULT不在列表中。

RawConfigParser.add_section(section)

将名为section的节添加到实例中。如果给定名称的部分已经存在,DuplicateSectionError则提出。如果名称DEFAULT(或其任何不区分大小写的变体)被传递,ValueError则会引发。

RawConfigParser.has_section(section)

指示命名节是否存在于配置中。该DEFAULT部分未被确认。

RawConfigParser.options(section)

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

RawConfigParser.has_option(section, option)

如果给定部分存在并包含给定选项,则返回True; 否则返回False

1.6版新增功能

RawConfigParser.read(filenames)

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

代码语言:javascript
复制
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)

将指定部分中选项强制为布尔值的简便方法。需要注意的是该选项的接受值是,,,和,导致该方法返回,和,,,和,这导致它返回。这些字符串值以不区分大小写的方式进行检查。任何其他价值都会导致它升高。"1""yes""true""on"True"0""no""false""off"FalseValueError

RawConfigParser.items(section)

返回(name, value)给定部分中每个选项的成对列表。

RawConfigParser.set(section, option, value)

如果给定部分存在,请将给定选项设置为指定值; 否则提出NoSectionError。尽管可以使用RawConfigParser(或ConfigParser原始参数设置为true)用于非字符串值的内部存储,但只能使用字符串值实现全部功能(包括插值和输出到文件)。

1.6版新增功能

RawConfigParser.write(fileobject)

将配置的表示写入指定的文件对象。这种表示可以通过未来的read()呼叫来解析。

1.6版新增功能

RawConfigParser.remove_option(section, option)

从指定部分删除指定的选项。如果该部分不存在,请提出。如果该选项存在被删除,则返回; 否则返回。NoSectionErrorTrueFalse

1.6版新增功能

RawConfigParser.remove_section(section)

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

RawConfigParser.optionxform(option)

转换在输入文件中找到的选项名称选项或由客户端代码传递到应在内部结构中使用的表单。默认实现返回一个小写版本的选项 ; 子类可能会覆盖此,或者客户端代码可以在实例上设置此名称的属性以影响此行为。

您不一定需要将ConfigParser的子类用于使用此方法,您还可以将其重置为实例,并将其设置为接受字符串参数的函数。str例如,将其设置为使选项名称区分大小写:

代码语言:javascript
复制
cfgparser = ConfigParser()
...
cfgparser.optionxform = str

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

2. ConfigParser对象

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

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

获取指定部分选项值。如果提供了vars,它必须是字典。该选项变量(如果提供),部分默认顺序中查找。

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

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

返回(name, value)给定部分中每个选项的成对列表。可选参数的含义与该get()方法相同。

2.3版本的新功能。

3. SafeConfigParser对象

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

SafeConfigParser.set(section, option, value)

如果给定部分存在,请将给定选项设置为指定值; 否则提出NoSectionError必须是一个字符串(strunicode); 如果没有,TypeError则会提出。

2.4版本中的新功能。

4.例子

写入配置文件的示例:

代码语言:javascript
复制
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)

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

代码语言:javascript
复制
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

代码语言:javascript
复制
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都提供默认值。如果使用的选项未在其他地方定义,它们将用于插值。

代码语言:javascript
复制
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下面的功能可用于在各部分之间移动选项:

代码语言:javascript
复制
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参数可以用来表示应该接受这样的值:

代码语言:javascript
复制
>>> 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'

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com