13.2.4 示例

写配置到文件

import ConfigParser

config = ConfigParser.RawConfigParser()

# 当往里面添加section或配置项时,你想要它们以怎样的顺序呈现, 就以相反的顺序进行添加
# 另外, 虽然你可以通过RawConfigParser实例或ConfigParser的raw模式给一个配置项设置非str值, 但是当你往文件输出或者以非raw模式读取时, 会抛出错误 
# SafeConfigParser实例不允许非str赋值.# 第四个参数指定时, magical interpolation键的替换值会优先从给定参数中获取
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')

要读取magical interpolation, 你需要使用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!"

# 第四个参数指定时, magical interpolation键的替换值会优先从给定参数中获取
print config.get('Section1', 'foo', 0, {'bar': 'Documentation',
                                        'baz': 'evil'})

默认值在3种ConifgParser对象中都可用, 通常在interpolation的替换项找不到时会去defaults中找

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

下面是一个将配置项从section1移到section2的实现

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参数为true来支持这一特性

>>> 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'# 当往里面添加section或配置项时,你想要它们以怎样的顺序呈现, 就以相反的顺序进行添加
# 另外, 虽然你可以通过RawConfigParser实例或ConfigParser的raw模式给一个配置项设置非str值, 但是当你往文件输出或者以非raw模式读取时, 会抛出错误 
# SafeConfigParser实例不允许非str赋值.

results matching ""

    No results matching ""