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

配置文件的格式

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

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

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

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

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

# 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 并加载配置文件

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

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

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) 读取指定的配置信息

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 是否存在

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

f) 设置 option

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

g) 删除 option

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/

更多 ConfigParser 的使用,参考:

Python(2.7.6) ConfigParser - 读写配置文件的更多相关文章

  1. ConfigParser 读写配置文件

    一.ini: 1..ini 文件是Initialization File的缩写,即初始化文件,是windows的系统配置文件所采用的存储格式 2.ini文件创建方法: (1)先建立一个记事本文件.(2 ...

  2. python利用ConfigParser读写配置文件

    ConfigParser 是Python自带的模块, 用来读写配置文件, 用法非常简单. 配置文件的格式是: []包含的叫section,    section 下有option=value这样的键值 ...

  3. Python模块之ConfigParser - 读写配置文件

    Python 标准库的 ConfigParser 模块提供一套 API 来读取和操作配置文件. 配置文件的格式 a) 配置文件中包含一个或多个 section, 每个 section 有自己的 opt ...

  4. Python-通过configparser读写配置文件

    Python读写配置文件: 1.创建配置文件(文件名以.conf或.ini结束的文件表示配置文件) 2.导入所需模块 OS, configparser >>> import os & ...

  5. 用ConfigParser模块读写配置文件——Python

    对于功能较多.考虑用户体验的程序,配置功能是必不可少的,如何存储程序的各种配置? 1)可以用全局变量,不过全局变量具有易失性,程序崩溃或者关闭之后配置就没了,再者配置太多,将变量分配到哪里也是需要考虑 ...

  6. 基于Python的接口自动化实战-基础篇之读写配置文件

    引言 在编写接口自动化测试脚本时,有时我们需要在代码中定义变量并给变量固定的赋值.为了统一管理和操作这些固定的变量,咱们一般会将这些固定的变量以一定规则配置到指定的配置文件中,后续需要用到这些变量和变 ...

  7. Python自动化测试 (二) ConfigParser模块读写配置文件

    ConfigParser 是Python自带的模块, 用来读写配置文件, 用法及其简单. 直接上代码,不解释,不多说. 配置文件的格式是: []包含的叫section,    section 下有op ...

  8. Python自动化测试 -ConfigParser模块读写配置文件

    C#之所以容易让人感兴趣,是因为安装完Visual Studio, 就可以很简单的直接写程序了,不需要做如何配置. 对新手来说,这是非常好的“初体验”, 会激发初学者的自信和兴趣. 而有些语言的开发环 ...

  9. python:实例化configparser模块读写配置文件

    之前的博客介绍过利用python的configparser模块读写配置文件的基础用法,这篇博客,介绍下如何实例化,方便作为公共类调用. 实例化的好处有很多,既方便调用,又降低了脚本的维护成本,而且提高 ...

随机推荐

  1. Eclipse Class Decompiler影响class默认打开方式,重新设置Eclipse默认源码打开方式

    安装Eclipse Class Decompiler插件后,Eclipse中的默认源码打开方式被修改为Eclipse Class Decompiler 这不是我喜欢的,因为我希望,源码从网络中获取,当 ...

  2. Navicat通过云主机内网连接阿里云RDS

    背景 公司为了安全起见,RDS设置只允许阿里云主机的内网端可以访问.这就意味,如果要操作RDS就需要连接到云主机上之后通过mysql shell操作.操作起来很复杂麻烦,今天看同事用Navicat f ...

  3. Spring配置文件的加载,及装载多个beans.xml文件

    applicationContext.xml 是spring的全局配置文件,用来控制srping的特性 1  手动加载自定义的beans.xml文件 @Test public void testAut ...

  4. excel 的一些操作

    unit Unit1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System ...

  5. [Objective-c 基础 - 2.11] SEL数据类型

    A.概念 1.SEL类型代表方法 2.每个方法都有一个对应的SEL类型的数据 3.实例对象调用方法 (1)编译器会把类的方法包装成SEL类型的数据, (2)根据SEL数据找到方法地址,缓存此地址 (3 ...

  6. 转载Linq中GroupBy方法的使用总结

    Group在SQL经常使用,通常是对一个字段或者多个字段分组,求其总和,均值等. Linq中的Groupby方法也有这种功能.具体实现看代码: 假设有如下的一个数据集: public class St ...

  7. ASP .Net提交时禁用Button

    转自:http://gaterking.blog.51cto.com/69893/301691/ 今天遇到一种小情况,想要在.net的服务器控件asp:button按下去时通过OnClientClic ...

  8. 对<< ubuntu 12.04编译安装linux-3.6.10内核笔记>>的修正

    前题: 在前几个月的时候,写了一篇笔记,说的是kernel compile的事情,当时经验不足,虽说编译过了,但有些地方写的有错误--因为当时的理解是有错误的.今天一一更正,记录如下: 前文笔记链接: ...

  9. iOS 关闭自动锁屏

    [UIApplication sharedApplication].idleTimerDisabled=YES;// 不自动锁屏 [UIApplication sharedApplication].i ...

  10. [Practical Git] Diagnose which commit broke something with git bisect

    Sometimes you find a bug in your project that has been around for a while without being noticed; it ...