ConfigParser模块

用于生成和修改常见配置文档,当前模块的名称在 python 3.x 版本中变更为 configparser。

ConfigParser方法
1、config=ConfigParser.ConfigParser()
创建ConfigParser实例

2、config.sections()
返回配置文件中节序列

3、config.options(section)
返回某个项目中的所有键的序列

4、config.get(section,option)
返回section节中,option的键值

5、config.add_section(str)
添加一个配置文件节点(str)

6、config.set(section,option,val)
设置section节点中,键名为option的值(val)

7、config.read(filename)
读取配置文件

8、config.write(obj_file)
写入配置文件
 

常见文档格式如下:

[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes
 
[bitbucket.org]
User = hg
 
[topsecret.server.com]
Port = 50022
ForwardX11 = no

用python生成一个这样的文档:

import configparser   #python3:cinfigparser;python2:ConfigParser

config = configparser.ConfigParser()
config["DEFAULT"] = {'ServerAliveInterval': '45',
                     'Compression': 'yes',
                     'CompressionLevel': '9'}

config['bitbucket.org'] = {}
config['bitbucket.org']['User'] = 'hg'
config['topsecret.server.com'] = {}
topsecret = config['topsecret.server.com']
topsecret['Host Port'] = '50022'  # mutates the parser
topsecret['ForwardX11'] = 'no'  # same here
config['DEFAULT']['ForwardX11'] = 'yes'
with open('example.ini', 'w') as configfile:
    config.write(configfile)

#读取
print(config.sections())
print(config.read('example.ini'))
print('bitbucket.org' in config)
print(config['bitbucket.org']['User'])
for key in config['bitbucket.org']:
    print(key)
secs = config.sections()
options = config.options('group2')
item_list = config.items('group2')
val1 = config.get('group1','key')
val2 = config.getint('group1','key')
print(secs,options,item_list,val1,val2)
#改写
sec = config.remove_section('group1')
config.write(open('i.cfg', "w"))

sec = config.has_section('wupeiqi')
sec = config.add_section('wupeiqi')
config.write(open('i.cfg', "w"))


config.set('group2','k1',11111)
config.write(open('i.cfg', "w"))

config.remove_option('group2','age')
config.write(open('i.cfg', "w"))

python 标准库的 ConfigParser 模块提供一套 API 来读取和操作配置文件。

配置文件的格式

a) 配置文件中包含一个或多个 section, 每个 section 有自己的 option;

b) section 用 [sect_name] 表示,每个option是一个键值对,使用分隔符 = 或 : 隔开;

c) 在 option 分隔符两端的空格会被忽略掉

d) 配置文件使用 # 和 ; 注释

一个简单的配置文件样例 myapp.conf

1

2

3

4

5

6

7

8

9

10

11

12

# database source

[db]

host = 127.0.0.1

port = 3306

user = root

pass = root

 

# ssh

[ssh]

host = 192.168.1.101

user = huey

pass = huey

 ConfigParser 的基本操作

a) 实例化 ConfigParser 并加载配置文件

1

2

cp = ConfigParser.SafeConfigParser()

cp.read('myapp.conf')

b) 获取 section 列表、option 键列表和 option 键值元组列表 

1

2

3

print 'all sections:', cp.sections()        # sections: ['db', 'ssh']

print 'options of [db]:', cp.options('db')  # options of [db]: ['host', 'port', 'user', 'pass']

print 'items of [ssh]:', cp.items('ssh')    # items of [ssh]: [('host', '192.168.1.101'), ('user', 'huey'), ('pass', 'huey')]

c) 读取指定的配置信息

1

2

print 'host of db:', cp.get('db''host')     # host of db: 127.0.0.1

print 'host of ssh:', cp.get('ssh''host')   # host of ssh: 192.168.1.101

d) 按类型读取配置信息:getint、 getfloat 和 getboolean


print type(cp.getint('db', 'port')) # <type 'int'>


e) 判断 option 是否存在

1

print cp.has_option('db''host')    # True  

f) 设置 option

1

cp.set('db''host','192.168.1.102')

g) 删除 option

1

cp.remove_option('db''host')

h) 判断 section 是否存在


print cp.has_section('db') # True


i) 添加 section


cp.add_section('new_sect')


j) 删除 section


cp.remove_section('db')


k) 保存配置,set、 remove_option、 add_section 和 remove_section 等操作并不会修改配置文件,write 方法可以将 ConfigParser 对象的配置写到文件中


cp.write(open('myapp.conf', 'w')) cp.write(sys.stdout)


Unicode 编码的配置

配置文件如果包含 Unicode 编码的数据,需要使用 codecs 模块以合适的编码打开配置文件。

myapp.conf


[msg] hello = 你好


config_parser_unicode.py

import ConfigParser
import codecs

cp = ConfigParser.SafeConfigParser()
with codecs.open('myapp.conf', 'r', encoding='utf-8') as f:
    cp.readfp(f)

print cp.get('msg', 'hello')

allow_no_value

通常情况下, option 是一个键值对。但是,当 SafeConfigParser 的参数 allow_no_value 设置成 True 时,它允许 option 不设置值而只是作为一个标识。

allow_no_value.conf

# option as Flag
[flag]
flag_opt

allow_no_value.py

import ConfigParser

cp = ConfigParser.SafeConfigParser(allow_no_value = True)
cp.read('myapp.conf')
print cp.get('flag', 'flag_opt');    # None

allow_no_value 默认设置成 False,此时如果配置文件中存在没有设置值的 option,在读取配置文件时将抛出异常  ConfigParser.ParsingError。当 allow_no_value 设置成 True 时,如果一个 option 没有设置值,has_option 方法会返回 True,get 方法会返回 None。

DEFAULT section

如果配置文件中存在一个名为 DEFAULT 的 section,那么其他 section 会扩展它的 option 并且可以覆盖它的 option。

db.conf

[DEFAULT]
host = 127.0.0.1
port = 3306

[db_root]
user = root
pass = root

[db_huey]
host = 192.168.1.101
user = huey
pass = huey

default_section.py

print cp.get('db_root', 'host')    # 127.0.0.1
print cp.get('db_huey', 'host')    # 192.168.1.101

插值 Interpolation

SafeConfigParser 提供了插值的特性来结合数据。

url.conf

[DEFAULT]
url = %(protocol)s://%(server)s:%(port)s/

[http]
protocol = http
server = localhost
port = 8080

[ftp]
url = %(protocol)s://%(server)s/
protocol = ftp
server = 192.168.1.102

interpolation_demo.py

import ConfigParser

cp = ConfigParser.SafeConfigParser()
cp.read('url.conf')

print cp.get('http', 'url')    # http://localhost:8080/
print cp.get('ftp', 'url')     # ftp://192.168.1.102/