python读取配置文件 ConfigParser
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.1port = 3306user = rootpass = root# ssh[ssh]host = 192.168.1.101user = hueypass = 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.1print '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/

更多 ConfigParser 的使用,参考:
http://blog.csdn.net/zm2714/article/details/8002125
python读取配置文件 ConfigParser的更多相关文章
- python 读取配置文件总是报错 configparser.NoSectionError: No section:
本文为作者原创,禁止转载,违者必究法律责任!!! python 读取配置文件总是报错 configparser.NoSectionError: No section: 无论是 python2的版本,还 ...
- python读取配置文件的方式
python读取配置文件的方式 1.从config.ini中读取,后缀无所谓,文件名字也无所谓,不过config.ini是常用写法,所谓见名知意 config.ini内容: [global] ip = ...
- python读取配置文件(ini、yaml、xml)
python读取配置文件(ini.yaml.xml)
- python中读取配置文件ConfigParser
在程序中使用配置文件来灵活的配置一些参数是一件很常见的事情,配置文件的解析并不复杂,在python里更是如此,在官方发布的库中就包含有做这件事情的库,那就是ConfigParser,这里简单的做一些介 ...
- python 读取配置文件ini ---ConfigParser
Python读取ini文件需要用到 ConfigParser 模块 关于ConfigParser模块的介绍详情请参照官网解释:https://docs.python.org/2.7/library/c ...
- python读取配置文件&&简单封装
之前有做过把爬虫数据写到数据库中的练习,这次想把数据库信息抽离到一个ini配置文件中,这样做的好处在于可以在配置文件中添加多个数据库,方便切换(另外配置文件也可以添加诸如邮箱.url等信息) 1.co ...
- Python操作配置文件configparser模块
在实际的开发过程中,我们常有操作ini格式和conf格式配置文件的操作,Python为我们提供了configparser模块,方便我们对配置文件进行读写操作. config.ini配置文件内容如下: ...
- Python+Selenium中级篇之-Python读取配置文件内容
本文来介绍下Python中如何读取配置文件.任何一个项目,都涉及到了配置文件和管理和读写,Python支持很多配置文件的读写,这里我们就介绍一种配置文件格式的读取数据,叫ini文件.Python中有一 ...
- 使用python读取配置文件并从mysql数据库中获取数据进行传参(基于Httprunner)
最近在使用httprunner进行接口测试,在传参时,用到了三种方法:(1)从csv文件中获取:(2)在config中声名然后进行引用:(3)从函数中获取.在测试过程中,往往有些参数是需要从数据库中获 ...
随机推荐
- Spring初学之annotation实现AOP前置通知、后置通知、返回通知、异常通知。
实现两个整数的加减乘除.在执行每个方法之前打印日志. ArithmeticCalculator.java: package spring.aop.impl; public interface Arit ...
- codeforces707A:Brain's Photos
Description Small, but very brave, mouse Brain was not accepted to summer school of young villains. ...
- python 2 到 3 的新手坑
print 和 input print 我们在课程最开始的时候就讲过 print,在版本2的使用方法是: print 'this is version 2' 也可以是 print('this is v ...
- Installing StackTach
为StackTach创建database,默认使用MySql,也可以 在settings.py 文件中配置其他的. create stack db mysql -u root -p mysql> ...
- Request对象获得参数方法:query和body方法
express框架Request对象获得参数方法:query和body方法 req.query 该属性用法很简单,直接获取地址栏传递的参数:例如: //引入依赖 var express = requi ...
- C语言基础三
C--数组 一维数组的定义和引用 定义:类型说明符 数组名[常量表达式] int a[ 10 ];他表示定义了一个整形数组,数组名为a,有10个元素. 注意:C语言不允许对数组的大小做动态定义. 一维 ...
- js动态拼接参数到请求的url上
var queryConfig={ "page" : "index", "method" : 2, //1:按照方法A查看 2:按照方法B查 ...
- LeetCode OJ:Length of Last Word(最后一个词的长度)
Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the l ...
- centos下安装storm
centOS安装ZeroMQ centOS安装ZeroMQ所需组件及工具: yum install gcc yum install gcc-c++ yum install make yum insta ...
- hdoj-3342-Legal or Not(拓扑排序)
题目链接 /* Name:hdoj-3342-Legal or Not Copyright: Author: Date: 2018/4/11 15:59:18 Description: 判断是否存在环 ...