ConfigParser模块 — 配置文件分析器

官方文档: https://docs.python.org/2/library/configparser.html

注意  

ConfigParser 模块在Python 3中已经重命名为 configparser.2to3 转换工具会自适应将要导入转成3中所需要包.

该模块定义了ConfigParser类,该类实现了基本的配置文件分析功能,和微软Windowns的INI文件架构非常类似。

用该模块可以很容易写客户自定义的Python的程序

注意 该库不能内插或写入值类型前缀,该功能仅能在Windows下扩展注册表的INI语法分析器版本中实现

另请参阅

模块   shlex
支持创建类unix的迷你语言,该语言能为应用配置文件创建交互式的格式
模块  json
该json模式实现了JAVA脚本语法的子集,该子集合能用作配置文件的目的

配置文件由sections组成,由[section]开头,后面接着name: value词目,附录见样式RFC 822;name=value方式也可以可以接受的。

注意空白行会从值中移除.可选的值包含指向同样的section或默认section中的值的格式化字符串。

附加的默认值能够在初始化和检索时提供.以'#'';'开始的行,会被忽视掉,通常用作注释.

配置文件可以包含注释,前缀由(# and ;)前缀.注释可以出现在空白行,或者section名或值后面。

在后面的情况下,必须在留有空格,这样就会被认为是注释.(当然这只是对;而言,而#就没有必须)

最核心的功能: 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提供,它将会为章节序列提供字典。

All option names are passed through the optionxform() method. Its default implementation converts option names to lower case.

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

Derived class of RawConfigParser that implements the magical interpolation feature and adds optional arguments to the get() and items() methods. The values in defaults must be appropriate for the %()s string interpolation. Note that __name__ is an intrinsic default; its value is the section name, and will override any value provided indefaults.

All option names used in interpolation will be passed through the optionxform() method just like any other option name reference. Using the default implementation ofoptionxform(), the values foo %(bar)s and foo %(BAR)s are equivalent.

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

Derived class of ConfigParser that implements a more-sane variant of the magical interpolation feature. This implementation is more predictable as well. New applications should prefer this version if they don’t need to be compatible with older versions of Python.

exception  ConfigParser. Error

所有其他的文件分析器基类异常

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

exception  ConfigParser. InterpolationSyntaxError

当替换源文件内容不符合所需的语法时触发的异常,其子类为:InterpolationError

exception  ConfigParser. MissingSectionHeaderError

当尝试分析一个没有以section开头的文件导致的异常

exception  ConfigParser. ParsingError

当尝试分析一个文件时出现错误时触发的异常

ConfigParser. MAX_INTERPOLATION_DEPTH

raw参数为假时,get()函数中最大循环内插深度,这个仅和ConfigParser类相关联

另请参阅

Module  shlex
支持创建类unix的迷你语言,该语言能为应用配置文件创建交互式的格式

  1. RawConfigParser Objects

RawConfigParser 实例有下面的方法:

RawConfigParser. defaults ( )

返回一个字典包含全实例的默认值

RawConfigParser. sections ( )

返回一个有效的section的列表,DEFAULT不包含在这个列表中.

RawConfigParser. add_section ( section )

增加一个section到实例中.如果给定的章节名已存在的话,会触发DuplicateSectionError异常。如果传递的值为DEFAULT,或任何大小写敏感的变量,会触发一个ValueError异常

RawConfigParser. has_section ( section )

显示section名是否已经在配置文件中存在,DEFAULT章节不被接受。

RawConfigParser. options ( section )

在专门的section中返回一个有效的section的列表

RawConfigParser. has_option ( sectionoption )

如果已给的section存在并包括已给的option的话,返回 True;否则返回 False

RawConfigParser. read ( filenames )

尝试读取并分析一个文件名列表,返回一个成功分析的文件名列表。 如果文件名是一个字符串或Unicode字符串.以单个文件名对待,如果文件不能被打开,则会被忽视。 

import ConfigParser, os

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



RawConfigParser. readfp ( fp [filename ] )

从一个文件或者类文件fp对象中读并分析配置文件(仅使用readline()方法),如果文件名被忽略并且有fp一个name属性,那么就会用作文件名,默认值为:<???>.

RawConfigParser. get ( sectionoption )

从命名的章节中获取选项值.

RawConfigParser. getint ( sectionoption )

一个很方便的方法,专门用来强制转换选项中的值为整数.

RawConfigParser. getfloat ( sectionoption )

一个很方便的方法,专门用来强制转换选项中的值为否点数.

RawConfigParser. getboolean ( sectionoption )

一个很方便的方法,专门用来强制转换选项中的值为布尔值.注意:可接受的值是:

"1""yes""true", and "on"=> True

"0""no""false", and "off"=> False。

这些字符串值是大小写敏感。任何其他的值会触发ValueError异常。 

RawConfigParser. items ( section )

为提供的章节的每个选项返回一个(name, value) 对。

RawConfigParser. set ( sectionoptionvalue )

如果提供的章节存在,那么设置为专门提供的值,否则会触发NoSectionError异常。

RawConfigParser. write ( fileobject )

写配置文件到专门的文件对象。该表示法能被read()方法调用。

RawConfigParser. remove_option ( sectionoption )

从指定的章节中移除可选项,如果章节不存在,则会触发NoSectionError异常。

如果已存在的选项被移除,会返回True,否则返回False.

RawConfigParser. remove_section ( section )

从配置文件中移除指定的章节。如果指定的章节的确存在的话,会返回True,否则返回False.

RawConfigParser. optionxform ( option )

Transforms the option name option as found in an input file or as passed in by client code to the form that should be used in the internal structures. The default implementation returns a lower-case version of option; subclasses may override this or client code can set an attribute of this name on instances to affect this behavior.

You don’t necessarily need to subclass a ConfigParser to use this method, you can also re-set it on an instance, to a function that takes a string argument. Setting it to str, for example, would make option names case sensitive:

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

Note that when reading configuration files, whitespace around the option names are stripped before optionxform() is called.

  2. ConfigParser Objects

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

ConfigParser. get ( sectionoption [raw [vars ] ] )

如果获得一个section下面的option值.如果vars提供,它必须是一个字典.如果vars参数提供的话,选项从section找,并按照默认的顺序.

所有的'%'内插都返回扩展值,除非raw参数为真.内插的对应键的值和选项中寻址方式一样.

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

如果返回一个(name, value)队.选项参数同get()方法具有同样的意思。


  3. SafeConfigParser Objects

SafeConfigParser类实现了的类似ConfigParser接口模块,下面是其增添部分:

SafeConfigParser.set(sectionoptionvalue)

如果给定的section存在的话,设置成专门的值;否则触发NoSectionError异常.值必须是个字符型(str或者unicode),

如果不是的话,会触发TypeError错误.

  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!')

# 写我们的配置文件到'example.cfg'中
with open('example.cfg', 'wb') as configfile:
    config.write(configfile)

下面是如何再次读取配置文件的例子:

import ConfigParser

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

# getfloat()函数会触发一个异常如果值不是浮点型
# getint()函数 和 getboolean()函数也会触发各自类型的异常错误
a_float = config.getfloat('Section1', 'a_float')
an_int = config.getint('Section1', 'an_int')
print a_float + an_int

# 注意下面的输出结果不会内插'%(bar)s' 或者 '%(baz)s'.
# 这是因为我们在用RawConfigParser()函数
if config.getboolean('Section1', 'a_bool'):
    print config.get('Section1', 'foo')

要想内插,需要使用ConfigParser类或者改类的方法SafeConfigParser:

import ConfigParser

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

# 设置第三可选参数为1如果你想使用原始的模式
print config.get('Section1', 'foo', 0) # -> "Python is fun!"
print config.get('Section1', 'foo', 1) # -> "%(bar)s is %(baz)s!"

# 第四可选项是一个字典,里面的成员在内插时可优先处理
print config.get('Section1', 'foo', 0, {'bar': 'Documentation',
                                        'baz': 'evil'})

一般来说:在三种ConfigParser类型都是使用默认值。他们用于插入如果选项没有在其他地方定义的话。

import ConfigParser

# 新实例用'bar' 和 'baz' 默认用 'Life' 和 'hard'取代
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:
        # 创建不存在的章节section2
        config.add_section(section2)
        opt_move(config, section1, section2, option)
    else:
        config.remove_option(section1, option)

一些配置文件无值设置其实早就为人所知,但是另外一方面讲也符合ConfigParser模块的支持。构造器允许无值参数暗示无值也是支持的。

>>>
>>> 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))

>>> # 如果选项中的值存在的话,则获取定义的值:
>>> config.get("mysqld", "user")
'mysql'

>>> # 如果选项中的值不存在的话,则获取默认值:None
>>> config.get("mysqld", "skip-bdb")

>>> # 如果选项本身都不存在的话,则会触发一个异常:
>>> config.get("mysqld", "does-not-exist")
Traceback (most recent call last):
  ...
ConfigParser.NoOptionError: No option 'does-not-exist' in section: 'mysqld'

相关文章:

http://scm.zoomquiet.io/data/20111111101002/index.html

http://www.cnblogs.com/TankXiao/p/3038350.html

http://wklken.me/posts/2012/02/19/python-ini-configparser.html

http://outofmemory.cn/code-snippet/1656/Python-usage-ConfigParser-duxie-ini-configuration-file



  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值