(转)python的ConfigParser模块
原文:https://blog.csdn.net/miner_k/article/details/77857292
如何使用Python3读写INI配置文件-------https://blog.csdn.net/willhuo/article/details/49512557
Python3 中 configparser 模块解析配置的用法详解------https://blog.csdn.net/geerniya/article/details/80083152
简介
ConfigParser
模块在python3中修改为configparser
.这个模块定义了一个ConfigParser类,该类的作用是使用配置文件生效,配置文件的格式和windows的INI文件的格式相同
该模块的作用 就是使用模块中的RawConfigParser()
、ConfigParser()
、 SafeConfigParser()
这三个方法(三者择其一),创建一个对象使用对象的方法对指定的配置文件做增删改查 操作。
配置文件有不同的片段组成和Linux中repo文件中的格式类似:
格式:
[section]
name=value
或者
name: value
"#" 和";" 表示注释
[DEFAULT] #设置默认的变量值,初始化
- 1
- 2
- 3
- 4
- 5
- 6
- 7
[My Section]
foodir: %(dir)s/whatever
dir=frob
long: this value continues
in the next line
- 1
- 2
- 3
- 4
- 5
- 6
%(dir)s
会被frob
代替。默认值会以字典的形式传递给ConfigParser的构造器。section一般存放的哦内置目录下,如果切换到其他的目录需啊哟指定存放位置。
方法
下面这三种方式使用时,切记注意
在调用这三个函数时,切记这三个函数会将调用optionxform()
,在传递键值对数据时,会将键名 全部转化为小写。
RawConfigParser()
ConfigParser.RawConfigParser([defaults[, dict_type[, allow_no_value]]])
defaults : 如果指定默认值,则使用默认值的键值对
dict_type:使用新的section的键值对
allow_no_value :默认是False,如果是True,表示可以接收空值(None)
return:对象
- 1
- 2
- 3
- 4
- 5
- 6
不支持可变参数,在section中不能存在%()s
ConfigParser()
ConfigParser.ConfigParser([defaults[, dict_type[, allow_no_value]]])
- 1
在default中必须出现%()s
SafeConfigParser()
ConfigParser.SafeConfigParser([defaults[, dict_type[, allow_no_value]]])
- 1
更加智能化,在section中是否存在%()s
会自动判断
传递参数使用函数optionxform(),foo %(bar)s 和 foo %(BAR)s是相同的,optionxform()会将大写字母全部转换为小写。
常见异常
异常 | 描述 |
---|---|
ConfigParser.Error | 所有异常的基类 |
ConfigParser.NoSectionError | 指定的section没有找到 |
ConfigParser.DuplicateSectionError | 调用add_section() 时,section名称已经被使用 |
ConfigParser.NoOptionError | 指定的参数没有找到 |
ConfigParser.InterpolationError | 当执行字符串插值时出现问题时,出现异常的基类 |
ConfigParser.InterpolationDepthError | 当字符串插值无法完成时,因为迭代次数超过了最大的范围,所以无法完成。InterpolationError的子类 |
InterpolationMissingOptionError | 当引用的选项不存在时,会出现异常。InterpolationError的子类 |
ConfigParser.InterpolationSyntaxError | 当产生替换的源文本不符合所需的语法时,就会出现异常。InterpolationError的子类。 |
ConfigParser.MissingSectionHeaderError | 当试图解析一个没有分段标题的文件时,会出现异常。 |
ConfigParser.ParsingError | 当试图解析文件时发生错误时,会出现异常 |
ConfigParser.MAX_INTERPOLATION_DEPTH | 当raw参数为false时,get()的递归插值的最大深度。这只适用于ConfigParser类 |
RawConfigParser 对象
对象的操作可以分为两大类,一种是对配置文件的操作,另一种是对读取后数据流的操作。
对配置文件的操作
读取配置文件
方法 | 描述 |
---|---|
read(filenames) | filesnames是一个列表,需要从文件加载初始值的应用程序应该在调用read()之前使用readfp()加载所需的文件或文件。 |
readfp(fp[, filename]) | 在fp中,从文件或文件类对象中读取和解析配置数据(只使用readline()方法)。如果文件名被省略,并且fp有一个name属性,它被用于文件名;默认值为< ? >。 |
写入配置文件
方法 | 描述 |
---|---|
write(fileobject) | 将配置的表示写入指定的文件对象。这个表示可以由未来的read()调用解析。 |
对内存中数据流的操作
增加配置文件中的值
方法 | 描述 |
---|---|
add_section(section) | 向实例添加一个section |
删除配置文件中的值
方法 | 描述 |
---|---|
remove_option(section, option) | 从指定的部分中删除指定的选项。如果该部分不存在,请提出NoSectionError。如果存在的选项被删除,返回True;否则返回False。 |
remove_section(section) | 从配置中删除指定的section。如果这个部分确实存在,返回True。否则返回假 |
修改配置文件中的值
方法 | 描述 |
---|---|
set(section, option, value) | 如果给定的部分存在,将给定的选项设置为指定的值 |
optionxform(option) | 也可以在一个实例上重新设置它,对于一个需要字符串参数的函数。例如,将其设置为str,将使选项名称区分大小写 |
查找配置文件中的值
方法 | 描述 |
---|---|
defaults() | 返回包含实例范围默认值的字典。 |
sections() | 返回可用的section的列表;默认section不包括在列表中 |
has_section(section) | 指示指定的section是否出现在配置中。默认的section未被确认 |
options(section) | 返回指定section中可用的选项列表。 |
has_option(section, option) | 如果给定的section存在,并且包含给定的选项,则返回True;否则返回False |
get(section, option) | 为指定的section获取一个选项值。 |
getint(section, option) | 它将指定section中的选项强制转换为整数 |
getfloat(section, option) | 它将指定section中的选项强制转换为浮点型 |
getboolean(section, option) | 强制转换为布尔型,”1”, “yes”, “true”, and “on”, 转换为True,”0”, “no”, “false”, and “off”, 转换为Falseo 其他返回ValueError. |
items(section) | 返回给定section中每个选项的(name,value)对的列表。 |
方法 | 描述 |
---|
import ConfigParser, os
config = ConfigParser.ConfigParser()
config.readfp(open('defaults.cfg'))
config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')])
- 1
- 2
- 3
- 4
- 5
- 6
cfgparser = ConfigParser()
...
cfgparser.optionxform = str
- 1
- 2
- 3
- 4
ConfigParser对象
SafeConfigParser中包含ConfigParser相同的方法,还有一部分增加的方法
方法 | 描述 |
---|---|
get(section, option[, raw[, vars]]) | 为指定的section获取一个选项值。如果提供了vars,它必须是一个字典。该选项在vars(如果提供)、分段和默认值中查找, |
items(section[, raw[, vars]]) | 返回给定section中每个选项的(名称、值)对的列表 |
所有的“%”插值都在返回值中展开,除非原始的参数是真的。内插键的值与选项相同
SafeConfigParser对象
set(section, option, value)
如果给定的部分存在,将给定的选项设置为指定的值;否则提高NoSectionError。值必须是字符串(str或unicode);如果没有,则会出现类型错误
实例
实例一:写配置文件
import ConfigParser
config = ConfigParser.RawConfigParser()
# When adding sections or items, add them in the reverse order of
# how you want them to be displayed in the actual file.
# In addition, please note that using RawConfigParser's and the raw
# mode of ConfigParser's respective set functions, you can assign
# non-string values to keys internally, but will receive an error
# when attempting to write to a file or when you get it in non-raw
# mode. SafeConfigParser does not allow such assignments to take place.
config.add_section('Section1')
config.set('Section1', 'an_int', '15')
config.set('Section1', 'a_bool', 'true')
config.set('Section1', 'a_float', '3.1415')
config.set('Section1', 'baz', 'fun')
config.set('Section1', 'bar', 'Python')
config.set('Section1', 'foo', '%(bar)s is %(baz)s!')
# Writing our configuration file to 'example.cfg'
with open('example.cfg', 'wb') as configfile:
config.write(configfile)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
实例二:读配置文件
import ConfigParser
config = ConfigParser.RawConfigParser()
config.read('example.cfg')
# getfloat() raises an exception if the value is not a float
# getint() and getboolean() also do this for their respective types
a_float = config.getfloat('Section1', 'a_float')
an_int = config.getint('Section1', 'an_int')
print a_float + an_int
# Notice that the next output does not interpolate '%(bar)s' or '%(baz)s'.
# This is because we are using a RawConfigParser().
if config.getboolean('Section1', 'a_bool'):
print config.get('Section1', 'foo')
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
实例三:获取插入值
import ConfigParser
config = ConfigParser.ConfigParser()
config.read('example.cfg')
# Set the third, optional argument of get to 1 if you wish to use raw mode.
print config.get('Section1', 'foo', 0) # -> "Python is fun!"
print config.get('Section1', 'foo', 1) # -> "%(bar)s is %(baz)s!"
# The optional fourth argument is a dict with members that will take
# precedence in interpolation.
print config.get('Section1', 'foo', 0, {'bar': 'Documentation',
'baz': 'evil'})
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
实例四:默认值
所有三种类型的config分析器都可以使用默认值。如果在其他地方没有定义一个选项,那么它们就被用于插值
import ConfigParser
# New instance with 'bar' and 'baz' defaulting to 'Life' and 'hard' each
config = ConfigParser.SafeConfigParser({'bar': 'Life', 'baz': 'hard'})
config.read('example.cfg')
print config.get('Section1', 'foo') # -> "Python is fun!"
config.remove_option('Section1', 'bar')
config.remove_option('Section1', 'baz')
print config.get('Section1', 'foo') # -> "Life is hard!"
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
实例五:在各section之间移动选项
def opt_move(config, section1, section2, option):
try:
config.set(section2, option, config.get(section1, option, 1))
except ConfigParser.NoSectionError:
# Create non-existent section
config.add_section(section2)
opt_move(config, section1, section2, option)
else:
config.remove_option(section1, option)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
实例六:配置文件中有空值
一些配置文件包含了没有值的设置,但是它与ConfigParser支持的语法相一致。对构造函数的不允许值参数可以被用来表示应该接受这样的值
>>> import ConfigParser
>>> import io
>>> sample_config = """
... [mysqld]
... user = mysql
... pid-file = /var/run/mysqld/mysqld.pid
... skip-external-locking
... old_passwords = 1
... skip-bdb
... skip-innodb
... """
>>> config = ConfigParser.RawConfigParser(allow_no_value=True)
>>> config.readfp(io.BytesIO(sample_config))
>>> # Settings with values are treated as before:
>>> config.get("mysqld", "user")
'mysql'
>>> # Settings without values provide None:
>>> config.get("mysqld", "skip-bdb")
>>> # Settings which aren't specified still raise an error:
>>> config.get("mysqld", "does-not-exist")
Traceback (most recent call last):
...
ConfigParser.NoOptionError: No option 'does-not-exist' in section: 'mysqld'
(转)python的ConfigParser模块的更多相关文章
- python封装configparser模块获取conf.ini值(优化版)
昨天晚上封装了configparser模块,是根据keyname获取的value.python封装configparser模块获取conf.ini值 我原本是想通过config.ini文件中的sect ...
- python中confIgparser模块学习
python中configparser模块学习 ConfigParser模块在python中用来读取配置文件,配置文件的格式跟windows下的ini配置文件相似,可以包含一个或多个节(section ...
- Python中ConfigParser模块应用
Python中ConfigParser模块应用 Python的ConfigParser模块定义了3个对INI文件进行操作的类 RawConfigParser.ConfigParser和SafeConf ...
- python中configparser模块读取ini文件
python中configparser模块读取ini文件 ConfigParser模块在python中用来读取配置文件,配置文件的格式跟windows下的ini配置文件相似,可以包含一个或多个节(se ...
- python 的ConfigParser模块
Python 之ConfigParser模块 一.ConfigParser简介 ConfigParser 是用来读取配置文件的包.配置文件的格式如下:中括号“[ ]”内包含的为section.sect ...
- Python自动化测试 -ConfigParser模块读写配置文件
C#之所以容易让人感兴趣,是因为安装完Visual Studio, 就可以很简单的直接写程序了,不需要做如何配置. 对新手来说,这是非常好的“初体验”, 会激发初学者的自信和兴趣. 而有些语言的开发环 ...
- python封装configparser模块获取conf.ini值
configparser模块是python自带的从文件中获取固定格式参数的模块,因为是python只带的,大家用的应该很多,我觉得这个参数模块比较灵活,添加参数.修改参数.读取参数等都有对应的参数供用 ...
- python中configparser模块的使用
configparser模块用于生成和修改常见配置文档,当前模块的名称在 python 3.x 版本中变更为 configparser. 首先要写一个如下所示的配置文件: [DEFAULT] serv ...
- python 配置文件 ConfigParser模块
ConfigParser模块 用于生成和修改常见配置文档,当前模块的名称在 python 3.x 版本中变更为 configparser. 来看一个好多软件的常见文档格式如下 [DEFAULT] Se ...
随机推荐
- linux命令详解之useradd命令使用方法[linux下 添加用户、删除用户、修改用户密码、用户组管理]
http://www.jb51.net/article/45848.htm Linux 系统是一个多用户多任务的分时操作系统,任何一个要使用系统资源的用户,都必须首先向系统管理员申请一个账号,然后以这 ...
- s4-介质访问控制子层-1 MAC子层
数据链路层被分成了两个子层:MAC和LLC MAC子层要解决什么问题? 介质访问控制(Madia Access Control) 数据通信方式 单播(unicast):One - to - One ...
- 如何在MYSQL下所有指定数据库名下执行SQL
mysql下用户库比较多,都有统一的命名格式,希望在这些所有用户库执行脚本,更新数据,或者查询数据 可以采用以下存储过程实现 DROP PROCEDURE IF EXISTS `sp_execalld ...
- python中的取整
处理数据时,经常会遇到取整的问题,现总结如下 1,向下取整 int() >>>a = 3.1 >>>b = 3.7 >>>int(a) 3 > ...
- Check the NativeLink log file
今天用Quartus ii16.1仿真Cyclone IV的IP核DDR2,总是报上面的错误 .网上都说是modelsim路径的问题, 但我确定不是.最后用QaurtusII 12.1可以通道仿真. ...
- java使用filter设置跨域访问
import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import ja ...
- day34(注解)
注解 注解和注释的区别: 注释:是给程序员看的. 注解:是给虚拟机识别的. 注解的作用: 1.代替配置文件 2.标识一个方法,代替一个特殊功能. JDK当中的提供的注解: 标识重写方法 @Overri ...
- MySQL性能优化之延迟关联
[背景] 某业务数据库load 报警异常,cpu usr 达到30-40 ,居高不下.使用工具查看数据库正在执行的sql ,排在前面的大部分是: SELECT id, cu_id, name, in ...
- HBase最佳实践(好文推荐)
HBase最佳实践-写性能优化策略 HBase最佳实践-管好你的操作系统 HBase最佳实践之列族设计优化 [大数据]HBase最佳实践 – 集群规划
- CI
做项目时,经常会碰到需要使用php的情况,自己也下决心把php好好学一下. 先从CI开始,再看一下项目中的php代码是如何写的.