此模块提供了一个实现基本配置语言的类

首先来看一个非常基本的配置文件,如下所示格式:

[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes [bitbucket.org]
User = hg [topsecret.server.com]
Port = 50022
ForwardX11 = no

可以通过编程的方式创建上述文件:

>>> import configparser
>>> config = configparser.ConfigParser()
>>> config['DEFAULT'] = {'ServerAliveInterval': '45',
... 'Compression': 'yes',
... 'CompressionLevel': '9'}
>>> config['bitbucket.org'] = {}
>>> config['bitbucket.org']['User'] = 'hg'
>>> config['topsecret.server.com'] = {}
>>> topsecret = config['topsecret.server.com']
>>> topsecret['Port'] = '50022' # mutates the parser
>>> topsecret['ForwardX11'] = 'no' # same here
>>> config['DEFAULT']['ForwardX11'] = 'yes'
>>> with open('example.ini', 'w') as configfile:
... config.write(configfile)
...

创建完毕之后我们可以通过以下代码来回读所记录的数据:

>>> import configparser
>>> config = configparser.ConfigParser()
>>> config.sections()
[]
>>> config.read('example.ini')
['example.ini']
>>> config.sections()
['bitbucket.org', 'topsecret.server.com']
>>> 'bitbucket.org' in config
True
>>> 'bytebong.com' in config
False
>>> config['bitbucket.org']['User']
'hg'
>>> config['DEFAULT']['Compression']
'yes'
>>> topsecret = config['topsecret.server.com']
>>> topsecret['ForwardX11']
'no'
>>> topsecret['Port']
'50022'
>>> for key in config['bitbucket.org']: print(key) # 默认值会一直存在
...
user
compressionlevel
serveraliveinterval
compression
forwardx11
>>> config['bitbucket.org']['ForwardX11']
'yes'


配置文件有几个部分组成:每个部分有[section]标题引导,其后跟着特定的字符串(=或:)分割键值对。默认情况下,节名称区分大小写。值可以跨越多行,只要他们比第一行缩进更深。

配置文件可以包括注释,通过特定的字符(#或;)表示。

例如:

[Simple Values]
key=value
spaces in keys=allowed
spaces in values=allowed as well
spaces around the delimiter = obviously
you can also use : to delimit keys from values [All Values Are Strings]
values like this: 1000000
or this: 3.14159265359
are they treated as numbers? : no
integers, floats and booleans are held as: strings
can use the API to get converted values directly: true [Multiline Values]
chorus: I'm a lumberjack, and I'm okay
I sleep all night and I work all day [No Values]
key_without_value
empty string value here = [You can use comments]
# like this
; or this # By default only in an empty line.
# Inline comments can be harmful because they prevent users
# from using the delimiting characters as parts of values.
# That being said, this can be customized. [Sections Can Be Indented]
can_values_be_as_well = True
does_that_mean_anything_special = False
purpose = formatting for readability
multiline_values = are
handled just fine as
long as they are indented
deeper than the first line
of a value
# Did I mention we can indent comments, too?



由于解析器并不会记录文件中值得数据类型,它始终以字符串的形式保存。因此简单的传递 bool() 函数并不会处理出正确结果,因为 bool('False') 仍然返回 True
配置器提供了一个方法 **getboolean()** 此方法可以识别 (不区分大小写)'yes'/ 'no','on'/ 'off', 'true'/ 'false'和'1'/ '0'中的布尔值。例如:
```python
# 上接上述配置代码
>>> topsecret.getboolean('ForwardX11')
False
>>> config['bitbucket.org'].getboolean('ForwardX11')
True
>>> config.getboolean('bitbucket.org', 'Compression')
True
# 此外,配置器还提供了 getint() 和 getfloat() 方法来处理数据类型
```

像字典一样,配置器提供了获取 section 值的方法 get()

>>> topsecret.get('Port')
'50022'
>>> topsecret.get('CompressionLevel')
'9'
>>> topsecret.get('Cipher')
>>> topsecret.get('Cipher', '3des-cbc')
'3des-cbc'

需要注意的是:默认值(default)优先于回退值(fallback),例如CompressionLevel密钥仅在该DEFAULT部分中指定。如果我们尝试topsecret.server.com部分获取它,即使我们指定了后备,我们也将始终获得默认值

>>> topsecret.get('CompressionLevel', '3')
'9'



以下是 configparser 模块的基本方法:
* 读取配置文件
1. defaults() 返回包含实例范围默认值的字典
2. read(filename) 直接读取ini文件内容
3. sections() 获取所有的 section,以列表的形式返回
4. options(section) 获取指定 section 的所有的 option
5. items(section) 获取指定 section 所有的键值对
6. get(section, option) 获取指定 section 中 option 的值
7. getint(section, option) 获取指定 section 中 option 的值,以 int 类型返回
8. getfloat(section, option) 获取指定 section 中 option 的值,以 float 类型返回
9. getboolean(section, option) 获取指定section 中 option 的值,以 boolean类型返回
* 写入配置文件
1. add_section(section) 添加指定的新的 section
2. has_section(section) 判断是否存在指定的 section
3. set(section, option, value) 设置指定 section 中 option 的值
4. remove_section(section) 删除指定 section
5. remove_option(section, option) 删除指定 section 中的 option
6. write(fileobject) 将内容写入配置文件

python configparser模块详解的更多相关文章

  1. python time模块详解

    python time模块详解 转自:http://blog.csdn.net/kiki113/article/details/4033017 python 的内嵌time模板翻译及说明  一.简介 ...

  2. python docopt模块详解

    python docopt模块详解 docopt 本质上是在 Python 中引入了一种针对命令行参数的形式语言,在代码的最开头使用 """ ""&q ...

  3. (转)python collections模块详解

    python collections模块详解 原文:http://www.cnblogs.com/dahu-daqing/p/7040490.html 1.模块简介 collections包含了一些特 ...

  4. python pathlib模块详解

    python pathlib模块详解    

  5. Python Fabric模块详解

    Python Fabric模块详解 什么是Fabric? 简单介绍一下: ​ Fabric是一个Python的库和命令行工具,用来提高基于SSH的应用部署和系统管理效率. 再具体点介绍一下,Fabri ...

  6. python time 模块详解

    Python中time模块详解 发表于2011年5月5日 12:58 a.m.    位于分类我爱Python 在平常的代码中,我们常常需要与时间打交道.在Python中,与时间处理有关的模块就包括: ...

  7. python常用模块详解

    python常用模块详解 什么是模块? 常见的场景:一个模块就是一个包含了python定义和声明的文件,文件名就是模块名字加上.py的后缀. 但其实import加载的模块分为四个通用类别: 1 使用p ...

  8. python os模块详解

    一.Python os模块(Linux环境) 1.1 执行shell命令 os.system('cmd') 执行命令不保存结果 os.popen('command') 执行后返回结果,使用.read( ...

  9. Python ZipFile模块详解(转)

    Python zipfile模块用来做zip格式编码的压缩和解压缩的,zipfile里有两个非常重要的class, 分别是ZipFile和ZipInfo, 在绝大多数的情况下,我们只需要使用这两个cl ...

随机推荐

  1. Windows中的"簇"和Linux中的"块"是对应的

    扇区是对硬盘而言,块是对文件系统而言. 簇”又称为“分配单元” ,文件系统是操作系统与驱动器之间的接口,当操作系统请求从硬盘里读取一个文件时,会请求相应的文件系统(FAT 16/32/NTFS)打开文 ...

  2. 牛客多校第六场 E Androgynos 自补图

    题意: 给定点数,构造自补图,要求输出邻接矩阵,和原图与补图的同构映射. 题解: 只有点数为4k和4k+1的情况才能构造自补图,因为只有这些情况下边数才为偶数. 一种构造方式是,邻接矩阵和同构映射增量 ...

  3. FTP Active & Passive

          在主动模式下,FTP客户端随机开启一个大于1024的端口N向服务器的21号端口发起连接,然后开放N+1号端口进行监听,并向服务器发出PORT N+1命令.服务器接收到命令后,会用其本地的F ...

  4. mfcs100d.lib(dllmodul.obj) : error LNK2005: _DllMain@12 already defined in MSVCRTD.lib(dllmain.obj)

    转自VC错误:http://www.vcerror.com/?p=55 问题描述: mfcs100d.lib(dllmodul.obj) : error LNK2005: _DllMain@12 al ...

  5. SCRIPT7002: XMLHttpRequest: 网络错误 0x2ef3的解决方法

    最近在使用jquery easyui datagrid 对页面布局,发现有时在IE下会接收不到数据并报错: SCRIPT7002: XMLHttpRequest: 网络错误 0x2ef3, 由于出现错 ...

  6. JAVA入门各种API参考

    java sdk: https://docs.oracle.com/javase/8/docs/api/ servlet api: http://tomcat.apache.org/tomcat-8. ...

  7. collections,time,random,os, sys 模块的使用

    主要内容:1. 模块的简单认识2. collections模块3. time时间模块4. random模块5. os模块6. sys模块 一. 模块的简单认识什么是模块. 模块就是我们把装有特定功能的 ...

  8. HTML中使用js的三种方式及优缺点介绍

    1.内部js: 在直接在页面的<script></script>标签内写js代码 优点:相对于使用行内js,内部js代码较为集中,与页面结构的实现代码耦合度较低,比较便于维护 ...

  9. 面试系列17 redis cluster

    1.redis cluster介绍 redis cluster (1)自动将数据进行分片,每个master上放一部分数据(2)提供内置的高可用支持,部分master不可用时,还是可以继续工作的 在re ...

  10. IoGetTopLevelIrp

    学习写驱动,其实,挺无聊,但是也挺有意思的 IoGetTopLevelIrp 今天在看一个文件系统过滤驱动的时候,看到这个函数,它是干嘛的,为什么会有这么个东西 https://msdn.micros ...