Python 之ConfigParser
2015-07-23 15:36
666 查看
http://blog.chinaunix.net/uid-25890465-id-3312861.html
一、ConfigParser简介
ConfigParser 是用来读取配置文件的包。配置文件的格式如下:中括号“[ ]”内包含的为section。section 下面为类似于key-value 的配置内容。
1: [db]
2: db_host = 127.0.0.1
3: db_port = 22
4: db_user = root
5: db_pass = rootroot
6:
7: [concurrent]
8: thread = 10
9: processor = 20
中括号“[ ]”内包含的为section。紧接着section 为类似于key-value 的options 的配置内容。
二、ConfigParser 初始工作
使用ConfigParser 首选需要初始化实例,并读取配置文件:
1: cf = ConfigParser.ConfigParser()
2: cf.read("配置文件名")
三、ConfigParser 常用方法
1. 获取所有sections。也就是将配置文件中所有“[ ]”读取到列表中:
1: s = cf.sections()
2: print 'section:', s
将输出(以下将均以简介中配置文件为例):
1: section: ['db', 'concurrent']
2. 获取指定section 的options。即将配置文件某个section 内key 读取到列表中:
1: o = cf.options("db")
2: print 'options:', o
将输出:
1: options: ['db_host', 'db_port', 'db_user', 'db_pass']
3. 获取指定section 的配置信息。
1: v = cf.items("db")
2: print 'db:', v
将输出:
1: db: [('db_host', '127.0.0.1'), ('db_port', '22'), ('db_user', 'root'), ('db_pass',
'rootroot')]
4. 按照类型读取指定section 的option 信息。
同样的还有getfloat、getboolean。
1: #可以按照类型读取出来
2: db_host = cf.get("db", "db_host")
3: db_port = cf.getint("db", "db_port")
4: db_user = cf.get("db", "db_user")
5: db_pass = cf.get("db", "db_pass")
6:
7: # 返回的是整型的
8: threads = cf.getint("concurrent", "thread")
9: processors = cf.getint("concurrent", "processor")
10:
11: print "db_host:",
db_host
12: print "db_port:",
db_port
13: print "db_user:",
db_user
14: print "db_pass:",
db_pass
15: print "thread:",
threads
16: print "processor:",
processors
将输出:
1: db_host: 127.0.0.1
2: db_port: 22
3: db_user: root
4: db_pass: rootroot
5: thread: 10
6: processor: 20
5. 设置某个option 的值。(记得最后要写回)
1: cf.set("db", "db_pass", "zhaowei")
2: cf.write(open("test.conf", "w"))
6.添加一个section。(同样要写回)
1: cf.add_section('liuqing')
2: cf.set('liuqing', 'int', '15')
3: cf.set('liuqing', 'bool', 'true')
4: cf.set('liuqing', 'float', '3.1415')
5: cf.set('liuqing', 'baz', 'fun')
6: cf.set('liuqing', 'bar', 'Python')
7: cf.set('liuqing', 'foo', '%(bar)s is %(baz)s!')
8: cf.write(open("test.conf", "w"))
7. 移除section 或者option 。(只要进行了修改就要写回的哦)
1: cf.remove_option('liuqing','int')
2: cf.remove_section('liuqing')
3: cf.write(open("test.conf", "w"))
点击(此处)折叠或打开
#!/usr/bin/env
python
from ConfigParser import ConfigParser
CONFIGFILE="f.txt"
config=ConfigParser()
config.read(CONFIGFILE)
print config.get('messages','greeting')
radius=input(config.get('messages','questions')+'
')
print config.get('messages','result')
print config.getfloat('numbers','pi')*radius**2
s=config.sections()
print'section: ',s
o=config.options('messages')
print'messages option: ',o
v=config.items("messages")
print'message de xinxi: ',v
config.add_section('liuyang1')
config.set('liuyang1','int','15')
config.set('liuyang'1,'hhhh','hello
world')
config.write(open("f.txt","w"))
print config.get('liuyang1','int')
print config.get('liuyang1','hhhh')
#!/usr/bin/env
python
import ConfigParser
import sys
config=ConfigParser.ConfigParser()
config.add_section("book1")
config.set("book1","title","hello
world")
config.set("book1","aut","log")
config.write(open("f.txt","w"))
功能介绍
在程序中使用配置文件来灵活的配置一些参数是一件很常见的事情,配置文件的解析并不复杂,在python里更是如此,在官方发布的库中就包含有做这件事情的库,那就是ConfigParser,这里简单的做一些介绍。
ConfigParser解析的配置文件的格式比较象ini的配置文件格式,就是文件中由多个section构成,每个section下又有多个配置项。
方法介绍:
Class RawConfigParser([defaults])
基本配置类,当传递defaults时,会初始化到内置字典中。该类不支持智能修复,2.3版本新特征。
Class ConfigParser([defaults])
继承之RawConfigParser类,实现了智能特性,为get(),items()方法添加了可选参数。Defaults中的值必须能填补“%()s”。注意__name__是内置的default;该值是section的名称,它会被defaults提供的任何值所覆盖。
所以的用于填补的option名称都会通过optionxform()方法传递,就像其他任何option名称一样。例如,使用optionxform()的默认实现(将option名称转化成小写),“foo %(bar)s”和“foo %(BAR)s”的值相等。
Class SafeConfigParser([defaults])
继承至ConfigParser,实现了更多智能特征,实现更有可预见性,新的应用更偏好这个版本,如果他们不需要对python老版本的兼容性,2.3版本。
Exception NoSectionError
当没有发现给定section时抛出。
Exception DuplicateSectionError
如果add_section()方法被调用时,提供的section参数的值已经存在时抛出。
Exception NoOptionError
指定option不存在时抛出。
Exception InterpolationError
执行字符串填补时抛出的异常的基类。
Exception InterpolationDepthError
当填补字符串因为迭代次数超过了MAX_INTERPOLATION_DEPTH值时抛出的异常,InterpolationError的子类。
Exception InterpolationMissingOptionError
当option引用的值不存在时抛出,该异常为InterpolationError的子类,2.3版本新加。
Exeption InterpolationSyntaxError
当原文件格式没有遵守规定的语法时抛出的异常,继承至InterpolationError,2.3版本。
Exception MissingSectionHeaderError
尝试解析没有section头的文件时抛出。
Exception ParsingError
解析文件时发生错误。
MAX_INTERPOLATION_DEPTH
get()方法当raw参数为false时,递归的对大深度。只适用与ConfigParser类。
RawConfigParser对象
RawConfigParser实例的方法:
defaults()
返回全部示例中所以defaults。
sections()
返回有效的section列表,DEFAULT不包含在列表中。
add_section(section)
为实例添加一个section,如果给定的section名已经存在,将抛出DuplicateSectionError异常。
has_section(section)
判断给定的section名在配置文件中是否存在,DEFAULT section不包括。
options(section)
返回给定的section下的所有可用option的列表。
has_option(section, option)
如果section存在,并包含给定的option,返回true,放在返回false, 1.6版本新增。
read(filenames)
尝试解析文件列表,如果解析成功返回文件列表。如果filenames是string或Unicode string,将会按单个文件来解析。如果在filenames中的文件不能打开,该文件将被忽略。这样设计的目的是,让你能指定本地有可能是配置文件的列表(例如,当前文件夹,用户的根目录,及一些全系统目录),所以在列表中存在的配置文件都会被读取。如果文件都不存在,那么ConfigParser实例会包含空数据集。一个需要从配置文件读取初始化数据的应用程序,应该使用readfp()方法来加载所需要的文件,之后可以使用read()方法来获取任何可能的文件:
import ConfigParser, os config = ConfigParser.ConfigParser()config.readfp(open(‘defaults.cfg’)) config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')])
2.4版本之后,返回成功解析的文件列表。
readfp(fp[, filename])
从文件或fp(值使用该对象的readline()方法)中的似文件类读取并解析配置数据,如果filename被省略,fp有一个name属性,该属性用于获取filename;默认是“”。
get(section, option)
获取section下option的值。
getint(section, option)
强制指定section下的option的值,作为Int类型返回的方便方法。
getfloat(section, option)
强制section下的option值,作为float类型返回的方法方法。
getboolean(section, option)
强制section下的option值,作为布尔类型返回的方法方法。注意可接受的option的true值有“1”,“yes”,“true”及“on”,可接受的false值有“0”,“no”,“false”,“off”。字符串值不检测大小写,其他值会抛出ValueError异常。
itmes(section)
返回给定section下的所以option的(name, value)对列表。
set(section, option, value)
如果给定的setion存在,为option设定给定的值;否则抛出NoSectionError异常。当可能使用RawConfigParser(或者ConfigParser的参数raw为true)来在内部存储非字符串值,所以功能(包括填补和输出到文件)只能使用字符串值来归档。1.6版本新增。
write(fileobject)
将配置表示写入指定文件类,该表示以后可以通过调用read()来解析,1.6版本新增。
remove_option(section, option)
从指定section中删除指定option,如果section不存在,抛出NoSectionError异常;如果option存在,则删除,并返回True;否则返回false。1.6版本新增。
remove_section(section)
从配置文件中删除指定的section,如果section确实存在,返回true,否则返回false。
optionxform(option)
将输入文件中,或客户端代码传递的option名转化成内部结构使用的形式。默认实现返回option的小写形式;子类可能重写该方法或客户端代码可能将该方法作为实例的属性,以此来影响它的行为。将此用于str(),例如,会使option名称大小写敏感。
ConfigParser对象
ConfigParser类扩展了RawConfigParser的一些接口方法,添加了一些可选参数。
get(section, option [, raw[, vars]])
获取给定section下的option的值,所以“%”占位符在返回值中被填补,基于构造时传递的默认值,就像option,vars也被提供,除非raw参数为true。
items(section, [, raw[, vars]])
返回给定section下的所以option的(name, value)对列表。可选参数同get方法,2.3版本新增。
SafeConfigParser对象
SafeConfigParser类实现了ConfigParser相同的接口,新增如下方法:
set(section, option, value)
如果给定的section存在,给option赋值;否则抛出NoSectionError异常。Value值必须是字符串(str或unicode);如果不是,抛出TypeError异常,2.4版本新增。
实际应用:
比如:
[db]
db_host=127.0.0.1
db_port=3306
db_user=root
db_pass=password
[concurrent]
thread=10
processor=20
假设上面的配置文件的名字为test.conf。里面包含两个section,一个是db, 另一个是concurrent, db里面还包含有4项,concurrent里面有两项。这里来做做解析:
#-*- encoding: gb2312 -*-
import ConfigParser
import string, os, syscf = ConfigParser.ConfigParser()
cf.read(“test.conf”)
# 返回所有的section
s = cf.sections()
print ’section:’, s
o = cf.options(“db”)
print ’options:’, o
v = cf.items(“db”)
print ’db:’, v
print ’-'*60
#可以按照类型读取出来
db_host = cf.get(“db”, ”db_host”)
db_port = cf.getint(“db”, ”db_port”)
db_user = cf.get(“db”, ”db_user”)
db_pass = cf.get(“db”, ”db_pass”)
# 返回的是整型的
threads = cf.getint(“concurrent”, ”thread”)
processors = cf.getint(“concurrent”, ”processor”)
print ”db_host:”, db_host
print ”db_port:”, db_port
print ”db_user:”, db_user
print ”db_pass:”, db_pass
print ”thread:”, threads
print ”processor:”, processors
#修改一个值,再写回去
cf.set(“db”, ”db_pass”, ”zhaowei”)
#Python
一、ConfigParser简介
ConfigParser 是用来读取配置文件的包。配置文件的格式如下:中括号“[ ]”内包含的为section。section 下面为类似于key-value 的配置内容。
1: [db]
2: db_host = 127.0.0.1
3: db_port = 22
4: db_user = root
5: db_pass = rootroot
6:
7: [concurrent]
8: thread = 10
9: processor = 20
中括号“[ ]”内包含的为section。紧接着section 为类似于key-value 的options 的配置内容。
二、ConfigParser 初始工作
使用ConfigParser 首选需要初始化实例,并读取配置文件:
1: cf = ConfigParser.ConfigParser()
2: cf.read("配置文件名")
三、ConfigParser 常用方法
1. 获取所有sections。也就是将配置文件中所有“[ ]”读取到列表中:
1: s = cf.sections()
2: print 'section:', s
将输出(以下将均以简介中配置文件为例):
1: section: ['db', 'concurrent']
2. 获取指定section 的options。即将配置文件某个section 内key 读取到列表中:
1: o = cf.options("db")
2: print 'options:', o
将输出:
1: options: ['db_host', 'db_port', 'db_user', 'db_pass']
3. 获取指定section 的配置信息。
1: v = cf.items("db")
2: print 'db:', v
将输出:
1: db: [('db_host', '127.0.0.1'), ('db_port', '22'), ('db_user', 'root'), ('db_pass',
'rootroot')]
4. 按照类型读取指定section 的option 信息。
同样的还有getfloat、getboolean。
1: #可以按照类型读取出来
2: db_host = cf.get("db", "db_host")
3: db_port = cf.getint("db", "db_port")
4: db_user = cf.get("db", "db_user")
5: db_pass = cf.get("db", "db_pass")
6:
7: # 返回的是整型的
8: threads = cf.getint("concurrent", "thread")
9: processors = cf.getint("concurrent", "processor")
10:
11: print "db_host:",
db_host
12: print "db_port:",
db_port
13: print "db_user:",
db_user
14: print "db_pass:",
db_pass
15: print "thread:",
threads
16: print "processor:",
processors
将输出:
1: db_host: 127.0.0.1
2: db_port: 22
3: db_user: root
4: db_pass: rootroot
5: thread: 10
6: processor: 20
5. 设置某个option 的值。(记得最后要写回)
1: cf.set("db", "db_pass", "zhaowei")
2: cf.write(open("test.conf", "w"))
6.添加一个section。(同样要写回)
1: cf.add_section('liuqing')
2: cf.set('liuqing', 'int', '15')
3: cf.set('liuqing', 'bool', 'true')
4: cf.set('liuqing', 'float', '3.1415')
5: cf.set('liuqing', 'baz', 'fun')
6: cf.set('liuqing', 'bar', 'Python')
7: cf.set('liuqing', 'foo', '%(bar)s is %(baz)s!')
8: cf.write(open("test.conf", "w"))
7. 移除section 或者option 。(只要进行了修改就要写回的哦)
1: cf.remove_option('liuqing','int')
2: cf.remove_section('liuqing')
3: cf.write(open("test.conf", "w"))
点击(此处)折叠或打开
#!/usr/bin/env
python
from ConfigParser import ConfigParser
CONFIGFILE="f.txt"
config=ConfigParser()
config.read(CONFIGFILE)
print config.get('messages','greeting')
radius=input(config.get('messages','questions')+'
')
print config.get('messages','result')
print config.getfloat('numbers','pi')*radius**2
s=config.sections()
print'section: ',s
o=config.options('messages')
print'messages option: ',o
v=config.items("messages")
print'message de xinxi: ',v
config.add_section('liuyang1')
config.set('liuyang1','int','15')
config.set('liuyang'1,'hhhh','hello
world')
config.write(open("f.txt","w"))
print config.get('liuyang1','int')
print config.get('liuyang1','hhhh')
#!/usr/bin/env
python
import ConfigParser
import sys
config=ConfigParser.ConfigParser()
config.add_section("book1")
config.set("book1","title","hello
world")
config.set("book1","aut","log")
config.write(open("f.txt","w"))
python ConfigParser模块详解
功能介绍在程序中使用配置文件来灵活的配置一些参数是一件很常见的事情,配置文件的解析并不复杂,在python里更是如此,在官方发布的库中就包含有做这件事情的库,那就是ConfigParser,这里简单的做一些介绍。
ConfigParser解析的配置文件的格式比较象ini的配置文件格式,就是文件中由多个section构成,每个section下又有多个配置项。
方法介绍:
Class RawConfigParser([defaults])
基本配置类,当传递defaults时,会初始化到内置字典中。该类不支持智能修复,2.3版本新特征。
Class ConfigParser([defaults])
继承之RawConfigParser类,实现了智能特性,为get(),items()方法添加了可选参数。Defaults中的值必须能填补“%()s”。注意__name__是内置的default;该值是section的名称,它会被defaults提供的任何值所覆盖。
所以的用于填补的option名称都会通过optionxform()方法传递,就像其他任何option名称一样。例如,使用optionxform()的默认实现(将option名称转化成小写),“foo %(bar)s”和“foo %(BAR)s”的值相等。
Class SafeConfigParser([defaults])
继承至ConfigParser,实现了更多智能特征,实现更有可预见性,新的应用更偏好这个版本,如果他们不需要对python老版本的兼容性,2.3版本。
Exception NoSectionError
当没有发现给定section时抛出。
Exception DuplicateSectionError
如果add_section()方法被调用时,提供的section参数的值已经存在时抛出。
Exception NoOptionError
指定option不存在时抛出。
Exception InterpolationError
执行字符串填补时抛出的异常的基类。
Exception InterpolationDepthError
当填补字符串因为迭代次数超过了MAX_INTERPOLATION_DEPTH值时抛出的异常,InterpolationError的子类。
Exception InterpolationMissingOptionError
当option引用的值不存在时抛出,该异常为InterpolationError的子类,2.3版本新加。
Exeption InterpolationSyntaxError
当原文件格式没有遵守规定的语法时抛出的异常,继承至InterpolationError,2.3版本。
Exception MissingSectionHeaderError
尝试解析没有section头的文件时抛出。
Exception ParsingError
解析文件时发生错误。
MAX_INTERPOLATION_DEPTH
get()方法当raw参数为false时,递归的对大深度。只适用与ConfigParser类。
RawConfigParser对象
RawConfigParser实例的方法:
defaults()
返回全部示例中所以defaults。
sections()
返回有效的section列表,DEFAULT不包含在列表中。
add_section(section)
为实例添加一个section,如果给定的section名已经存在,将抛出DuplicateSectionError异常。
has_section(section)
判断给定的section名在配置文件中是否存在,DEFAULT section不包括。
options(section)
返回给定的section下的所有可用option的列表。
has_option(section, option)
如果section存在,并包含给定的option,返回true,放在返回false, 1.6版本新增。
read(filenames)
尝试解析文件列表,如果解析成功返回文件列表。如果filenames是string或Unicode string,将会按单个文件来解析。如果在filenames中的文件不能打开,该文件将被忽略。这样设计的目的是,让你能指定本地有可能是配置文件的列表(例如,当前文件夹,用户的根目录,及一些全系统目录),所以在列表中存在的配置文件都会被读取。如果文件都不存在,那么ConfigParser实例会包含空数据集。一个需要从配置文件读取初始化数据的应用程序,应该使用readfp()方法来加载所需要的文件,之后可以使用read()方法来获取任何可能的文件:
import ConfigParser, os config = ConfigParser.ConfigParser()config.readfp(open(‘defaults.cfg’)) config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')])
2.4版本之后,返回成功解析的文件列表。
readfp(fp[, filename])
从文件或fp(值使用该对象的readline()方法)中的似文件类读取并解析配置数据,如果filename被省略,fp有一个name属性,该属性用于获取filename;默认是“”。
get(section, option)
获取section下option的值。
getint(section, option)
强制指定section下的option的值,作为Int类型返回的方便方法。
getfloat(section, option)
强制section下的option值,作为float类型返回的方法方法。
getboolean(section, option)
强制section下的option值,作为布尔类型返回的方法方法。注意可接受的option的true值有“1”,“yes”,“true”及“on”,可接受的false值有“0”,“no”,“false”,“off”。字符串值不检测大小写,其他值会抛出ValueError异常。
itmes(section)
返回给定section下的所以option的(name, value)对列表。
set(section, option, value)
如果给定的setion存在,为option设定给定的值;否则抛出NoSectionError异常。当可能使用RawConfigParser(或者ConfigParser的参数raw为true)来在内部存储非字符串值,所以功能(包括填补和输出到文件)只能使用字符串值来归档。1.6版本新增。
write(fileobject)
将配置表示写入指定文件类,该表示以后可以通过调用read()来解析,1.6版本新增。
remove_option(section, option)
从指定section中删除指定option,如果section不存在,抛出NoSectionError异常;如果option存在,则删除,并返回True;否则返回false。1.6版本新增。
remove_section(section)
从配置文件中删除指定的section,如果section确实存在,返回true,否则返回false。
optionxform(option)
将输入文件中,或客户端代码传递的option名转化成内部结构使用的形式。默认实现返回option的小写形式;子类可能重写该方法或客户端代码可能将该方法作为实例的属性,以此来影响它的行为。将此用于str(),例如,会使option名称大小写敏感。
ConfigParser对象
ConfigParser类扩展了RawConfigParser的一些接口方法,添加了一些可选参数。
get(section, option [, raw[, vars]])
获取给定section下的option的值,所以“%”占位符在返回值中被填补,基于构造时传递的默认值,就像option,vars也被提供,除非raw参数为true。
items(section, [, raw[, vars]])
返回给定section下的所以option的(name, value)对列表。可选参数同get方法,2.3版本新增。
SafeConfigParser对象
SafeConfigParser类实现了ConfigParser相同的接口,新增如下方法:
set(section, option, value)
如果给定的section存在,给option赋值;否则抛出NoSectionError异常。Value值必须是字符串(str或unicode);如果不是,抛出TypeError异常,2.4版本新增。
实际应用:
比如:
[db]
db_host=127.0.0.1
db_port=3306
db_user=root
db_pass=password
[concurrent]
thread=10
processor=20
假设上面的配置文件的名字为test.conf。里面包含两个section,一个是db, 另一个是concurrent, db里面还包含有4项,concurrent里面有两项。这里来做做解析:
#-*- encoding: gb2312 -*-
import ConfigParser
import string, os, syscf = ConfigParser.ConfigParser()
cf.read(“test.conf”)
# 返回所有的section
s = cf.sections()
print ’section:’, s
o = cf.options(“db”)
print ’options:’, o
v = cf.items(“db”)
print ’db:’, v
print ’-'*60
#可以按照类型读取出来
db_host = cf.get(“db”, ”db_host”)
db_port = cf.getint(“db”, ”db_port”)
db_user = cf.get(“db”, ”db_user”)
db_pass = cf.get(“db”, ”db_pass”)
# 返回的是整型的
threads = cf.getint(“concurrent”, ”thread”)
processors = cf.getint(“concurrent”, ”processor”)
print ”db_host:”, db_host
print ”db_port:”, db_port
print ”db_user:”, db_user
print ”db_pass:”, db_pass
print ”thread:”, threads
print ”processor:”, processors
#修改一个值,再写回去
cf.set(“db”, ”db_pass”, ”zhaowei”)
#Python
相关文章推荐
- python数据存储 pprint, pickle
- 迭代和递归(Python)--乘方、最大公约数、汉诺塔、斐波那契、回文字符串
- Python-goose:用于文章提取的Python库
- python-celery使用教程
- python的初级训练
- python-ConfigParser模块【读写配置文件】
- python字符串连接
- 【转】Python的异常处理机制
- 使用Python生成pdf文件
- [python]csv格式文件的使用
- 使用python进行机械设计计算
- Python学习之List
- 1.python环境搭建(python2.7.10+ PyCharm3.4.1/eclipse+selenium)
- 有关Python应用的21个小技巧
- python的基础概念
- python getopt使用
- python常见错误总结结
- python 元祖,列表,字典 初识
- Python Technical Notes
- python的unittest测试框架的扩展浅谈