Python模块之ConfigParser

来源:互联网 发布:淘宝店铺怎么免费推广 编辑:程序博客网 时间:2024/05/19 02:39

原文:http://www.cnblogs.com/victorwu/p/5762931.html

注:从配置文件中读取到的数据格式都为str

配置文件的格式

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

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

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

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

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

# database source[db]host = 127.0.0.1port = 3306user = rootpass = root[ssh]host = 192.168.1.101user = hueypass = huey

读取配置文件

# 实例化 ConfigParsercp = ConfigParser.SafeConfigParser()# 加载配置文件cp.read('myapp.conf')

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

# 获取配置文件中所有section,返回的结果为list类型cp.sections() # sections: ['db', 'ssh']# 获取配置文件中sections=db的option的键cp.options('db')  # [db]: ['host', 'port', 'user', 'pass']# 获取配置文件中sections=ssh的键值对cp.items('ssh') # [('host', '192.168.1.101'), ('user', 'huey'), ('pass', 'huey')]


读取指定的配置信息

# 判断sectino=db是否存在cp.has_section('db')# 判断 section=db 下的option=host 是否存在cp.has_option('db', 'host')# 添加 section=new_sectcp.add_section('new_sect')# 读取指定的配置信息cp.get('db', 'host') # db: 127.0.0.1# 设置 section=db下的host=192.168.1.102cp.set('db', 'host','192.168.1.102')# 删除 section=dbcp.remove_section('db')#  删除 section=db下的option=hsotcp.remove_option('db', 'host')

注:以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 ConfigParserimport codecscp = ConfigParser.SafeConfigParser()with codecs.open('myapp.conf', 'r', encoding='utf-8') as f:    cp.readfp(f)print cp.get('msg', 'hello')
DEFAULT section

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

[DEFAULT]host = 127.0.0.1port = 3306[db_root]user = rootpass = root[db_huey]host = 192.168.1.101user = hueypass = huey

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

插值 Interpolation

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

[DEFAULT]url = %(protocol)s://%(server)s:%(port)s/[http]protocol = httpserver = localhostport = 8080[ftp]url = %(protocol)s://%(server)s/protocol = ftpserver = 192.168.1.102

-------------------------------------------
import ConfigParsercp = ConfigParser.SafeConfigParser()cp.read('url.conf')print cp.get('http', 'url')    # http://localhost:8080/print cp.get('ftp', 'url')     # ftp://192.168.1.102/




原创粉丝点击