一、概述

在软件开发过程中,很多时候需要处理配置文件的读取解析和改写,在python中专门处理配置文件的模块就是configpaser了。顾名思义,configpaser就是配置解析器,可用来对符合格式规范的.conf,ini等配置文件进行解析读取,并支持增删改查、定义新的配置文件等处理。

二、配置文件格式规范

可以被configpaser处理的配置文件需符合以下格式规范:

  1. 1 [mysqld]
  2. 2 datadir=/var/lib/mysql
  3. 3 socket=/var/lib/mysql/mysql.sock
  4. 4 user=mysql
  5. 5 # Disabling symbolic-links is recommended to prevent assorted security risks
  6. 6 symbolic-links=0
  7. 7 character-set-server=utf8
  8. 8
  9. 9 [mysqld_safe]
  10. 10 log-error=/var/log/mysqld.log
  11. 11 pid-file=/var/run/mysqld/mysqld.pid
  12. 12
  13. 13 [client]
  14. 14 default-character-set=utf8
  15. 15
  16. 16 [mysql]
  17. 17 default-character-set=utf8

细心的同学可发现这就是mysql的默认配置文件,类似的还有ansible的hosts文件:

  1. 1 [group1]
  2. 2 host1 var1=value1 var2=value2
  3. 3 host2 var3=value2
  4. 4 [group2]
  5. 5 host3
  6. 6 [group1:children]
  7. 7 group2

三、configpaser的常见用法

前文提到,configpaser支持对配置文件的解析读取、增删改查和定义新的配置文件等处理,可满足不同场景下对配置文件的处理需求,下面我们先来创建一个示例配置文件,然后逐一详述读取和增删改查用法。

3.1 创建配置文件

创建示例配置文件

  1. 1 import configparser
  2. 2
  3. 3 config = configparser.ConfigParser()
  4. 4 #开始创建第一个section,类似于list赋值方式,值为dict
  5. 5 config['DEFAULT'] = {'compressionlevel': '9',
  6. 6 'serveraliveinterval': '45',
  7. 7 'compression': 'yes'}
  8. 8 config['DEFAULT']['forwardx11'] = 'yes'
  9. 9 #创建第二个section
  10. 10 config['bitbucket.org'] = {}
  11. 11 #类似于通过list的下标来赋值元素
  12. 12 config['bitbucket.org']['user'] = 'hg'
  13. 13 config['topsecret.server.com'] = {}
  14. 14 #通过中间变量来替代
  15. 15 topsecret = config['topsecret.server.com']
  16. 16 topsecret['host port'] = '50022'
  17. 17 topsecret['forwardx11'] = 'no'
  18. 18 #开始写入配置文件
  19. 19 with open('test.conf', 'w', encoding='utf-8') as configfile:
  20. 20 config.write(configfile)

注意:
创建的key-value中里面如果有数字,需要加引号变成string形式,否则会报数据类型错误。

创建的配置文件显示如下:

  1. 1 [DEFALUT]
  2. 2 compressionlevel = 9
  3. 3 serveraliveinterval = 45
  4. 4 compression = yes
  5. 5 forwardx11 = yes
  6. 6
  7. 7 [bitbucket.org]
  8. 8 user = hg
  9. 9
  10. 10 [topsecret.server.com]
  11. 11 host port = 50022
  12. 12 forwardx11 = no

3.2 读取配置文件

很多场景下我们更多的是需要解析读取其他软件的配置文件,以获取相关的参数信息。

  • 读取section
    section即符合格式规范的配置文件的一级目录,方括号[]包含的部分.sections()方法用于获取配置文件的除default外的所有section,以list形式返回
    1. 1 >>> import configparser
    2. 2 >>> config = configparser.ConfigParser()
    3. 3 >>> config.sections() #获取section
    4. 4 []
    5. 5 >>> config.read('test.conf') #读取配置文件
    6. 6 ['test.conf']
    7. 7 >>> config.sections() #成功返回section,但不包括default
    8. 8 ['bitbucket.org', 'topsecret.server.com']
    9. 9 >>> config.defaults() #返回default section的键值对
    10. 10 OrderedDict([('compressionlevel', '9'), ('serveraliveinterval', '45'), ('compres
    11. 11 sion', 'yes'), ('forwardx11', 'yes')])
  • 判断section是否存在
    1. 1 >>> 'bitbucket.org' in config
    2. 2 True
    3. 3 >>> 'bitbucket.org1' in config
    4. 4 False
    5. 5 >>> 'DEFAULT' in config
    6. 6 True
    7. 7 >>>
  • 读取section内的值
    获取某个key对应的value可以以类似于list下标的形式获取,options()方法可获取指定section和default在内的所有key,items可获取指定section和default在内的所有key-value对
    1. 1 >>> config.options('bitbucket.org')
    2. 2 ['user', 'compressionlevel', 'serveraliveinterval', 'compression', 'forwardx11']
    3. 3 >>> config.items('bitbucket.org')
    4. 4 [('compressionlevel', '9'), ('serveraliveinterval', '45'), ('compression', 'yes'),('forwardx11', 'yes'), ('user', 'hg')]
    5. 5 >>> config['bitbucket.org']['user']
    6. 6 'hg'
    7. 7 >>>
  • 循环获取section内的key值
    可以通过config[‘section_name’]的方式循环获取,也可以通过options方法循环获取
    1. 1 >>> for key in config['bitbucket.org']:
    2. 2 ... print(key)
    3. 3 ...
    4. 4 user
    5. 5 compressionlevel
    6. 6 serveraliveinterval
    7. 7 compression
    8. 8 forwardx11
    9. 9 >>>
    10. 10
    11. 11 >>> for key in config.options('bitbucket.org'):
    12. 12 ... print(key)
    13. 13 ...
    14. 14 user
    15. 15 compressionlevel
    16. 16 serveraliveinterval
    17. 17 compression
    18. 18 forwardx11

3.3 configpaser的增删改查

  • 读取
    主要的读取方法如下:
  • -read(filename)               直接读取文件内容

    -sections()                      得到所有的section,并以列表的形式返回

    -options(section)             得到该section的所有option

    -items(section)                得到该section的所有键值对

    -get(section,option)         得到section中option的值,返回为string类型

    -getint(section,option)      得到section中option的值,返回为int类型,还有相应的getboolean()和getfloat() 函数。

    1. 1 import configparser
    2. 2
    3. 3 config = configparser.ConfigParser()
    4. 4 config.read('test.conf')
    5. 5
    6. 6 print(config.sections())
    7. 7 print(config.options('topsecret.server.com'))
    8. 8 print(config.items('topsecret.server.com'))
    9. 9 print(config.get('topsecret.server.com', 'host port'))
    10. 10 print(type(config.get('topsecret.server.com', 'host port')))
    11. 11 print(config.getint('topsecret.server.com', 'host port'))
    12. 12 print(type(config.getint('topsecret.server.com', 'host port')))
    13. 13
    14. 14
    15. 15 程序输出:
    16. 16 ['bitbucket.org', 'topsecret.server.com']
    17. 17 ['host port', 'forwardx11', 'compressionlevel', 'serveraliveinterval', 'compression']
    18. 18 [('compressionlevel', '9'), ('serveraliveinterval', '45'), ('compression', 'yes'), ('forwardx11', 'no'), ('host port', '50022')]
    19. 19 50022
    20. 20 <class 'str'>
    21. 21 50022
    22. 22 <class 'int'>

    注意:
    default是一个特殊的全局section,我们获取section时不会返回它,但是当我们在获取其他section的key或者key-value对时,会包括default相应的内容,可以认为它是一个全局缺省的section把。

  • 更改
    通过set方式可实现对已有key-value的修改,如果set的对象不存在,则报错该section不存在
    1. 1 import configparser
    2. 2
    3. 3 config = configparser.ConfigParser()
    4. 4 config.read('test.conf')
    5. 5
    6. 6 print(config.get('topsecret.server.com', 'host port'))
    7. 7 config.set('topsecret.server.com', 'host port' ,'60022')
    8. 8 print(config.get('topsecret.server.com', 'host port'))
    9. 9
    10. 10 结果输出:
    11. 11 50022
    12. 12 60022
  • 增加
    新增section:
    1. 1 >>> import configparser
    2. 2 >>> config = configparser.ConfigParser()
    3. 3 >>> config.read('test.conf')
    4. 4 ['test.conf']
    5. 5 >>> config.has_section('topsecret.server.com')
    6. 6 True
    7. 7 >>> config.has_section('sync_data') #判断是否有该section
    8. 8 False
    9. 9 >>> config.options('topsecret.server.com')
    10. 10 ['host port', 'forwardx11', 'compressionlevel', 'serveraliveinterval', 'compress
    11. 11 ion']
    12. 12 >>> config.add_section('sync_data') #新增section
    13. 13 >>> config.sections() #新增成功
    14. 14 ['bitbucket.org', 'topsecret.server.com', 'sync_data']

  • 新增option:
    set还有一种用法是为一个存在的section新增option:

    1. 1 import configparser
    2. 2
    3. 3 config = configparser.ConfigParser()
    4. 4 config.read('test.conf')
    5. 5
    6. 6 print(config.options('topsecret.server.com'))
    7. 7 #新增option autoreload
    8. 8 config.set('topsecret.server.com', 'autoreload' ,'yes')
    9. 9 print(config.options('topsecret.server.com'))
    10. 10 print(config.items('topsecret.server.com'))
    11. 11
    12. 12 程序输出:
    13. 13 ['host port', 'forwardx11', 'compressionlevel', 'serveraliveinterval', 'compression']
    14. 14 ['host port', 'forwardx11', 'autoreload', 'compressionlevel', 'serveraliveinterval', 'compression']
    15. 15 [('compressionlevel', '9'), ('serveraliveinterval', '45'), ('compression', 'yes'), ('forwardx11', 'no'), ('host port', '50022'), ('autoreload', 'yes')]
    16. 16 #新增option后可以看到多出autoreload,items也能返回它对应的value
  • 删除

    1. 1 >>> import configparser
    2. 2 >>> config = configparser.ConfigParser()
    3. 3 >>> config.read('test.conf')
    4. 4 ['test.conf']
    5. 5 >>> config.sections()
    6. 6 ['bitbucket.org', 'topsecret.server.com']
    7. 7
    8. 8 #开始删除section
    9. 9 >>> config.remove_section('bitbucket.org')
    10. 10 True
    11. 11 >>> config.sections()
    12. 12 ['topsecret.server.com'] #成功删除section
    13. 13
    14. 14 >>> config.options('topsecret.server.com')
    15. 15 ['host port', 'forwardx11', 'compressionlevel', 'serveraliveinterval', 'com
    16. 16 ion']
    17. 17 #开始删除option
    18. 18 >>> config.remove_option('topsecret.server.com','host port')
    19. 19 True
    20. 20 >>> config.options('topsecret.server.com')
    21. 21 ['forwardx11', 'compressionlevel', 'serveraliveinterval', 'compression'] #成功删除option
    22. 22
    23. 23 #删除默认的default的option失败
    24. 24 >>> config.remove_option('topsecret.server.com','compression')
    25. 25 False
    26. 26 >>> config.options('topsecret.server.com')
    27. 27 ['forwardx11', 'compressionlevel', 'serveraliveinterval', 'compression']

注意:如果要删除default的全局默认option,必须指定section为default后才能删除 

  1. 1 >>> config.remove_option('DEFAULT','compression')
  2. 2 True
  3. 3 >>> config.options('topsecret.server.com')
  4. 4 ['forwardx11', 'compressionlevel', 'serveraliveinterval']

  • 持久化保存
    上述增、删、改的操作都只是处理了内存中的对象,并没有进行持久化保存,会面临一个重新read后修改又被回滚的问题,这时切记修改完了要立即进行持久化保存处理。保存方法与操作普通文件非常类似:
    1. 1 >>> import configparser
    2. 2 >>> config = configparser.ConfigParser()
    3. 3 >>> config.read('test.conf')
    4. 4 >>> with open('test.conf','w',encoding='utf-8') as configfile:
    5. 5 ... config.write(configfile)
    6. 6 ...
    7. 7 >>> config.read('test.conf')
    8. 8 ['test.conf']
    9. 9 #持久化保存后重新读取,此前的修改已经生效
    10. 10 >>> config.sections()
    11. 11 ['topsecret.server.com']
    12. 12 >>> config.options('topsecret.server.com')
    13. 13 ['forwardx11', 'compressionlevel', 'serveraliveinterval']

持久化保存时可指定保存到源文件进行覆盖写处理,也可以另存为其他文件。

day5-configparser模块的更多相关文章

  1. 小白的Python之路 day5 configparser模块的特点和用法

    configparser模块的特点和用法 一.概述 主要用于生成和修改常见配置文件,当前模块的名称在 python 3.x 版本中变更为 configparser.在python2.x版本中为Conf ...

  2. day5模块学习--configparser模块

       使用ConfigParser模块读写ini文件(http://blog.csdn.net/linda1000/article/details/11729561) ConfigParserPyth ...

  3. Python学习-day5 常用模块

    day5主要是各种常用模块的学习 time &datetime模块 random os sys shutil json & picle shelve xml处理 yaml处理 conf ...

  4. configparser模块

    configparser模块 echo   $@ $# $? $* configparse用于处理特定格式的文件,其本质上利用open来操作文件(比如配置文件) **********配置文件***** ...

  5. Python 之路 Day5 - 常用模块学习

    本节大纲: 模块介绍 time &datetime模块 random os sys shutil json & picle shelve xml处理 yaml处理 configpars ...

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

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

  7. python 学习day5(模块)

    一.模块介绍 模块,用一砣代码实现了某个功能的代码集合. 类似于函数式编程和面向过程编程,函数式编程则完成一个功能,其他代码用来调用即可,提供了代码的重用性和代码间的耦合.而对于一个复杂的功能来,可能 ...

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

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

  9. Python学习笔记——基础篇【第六周】——PyYAML & configparser模块

    PyYAML模块 Python也可以很容易的处理ymal文档格式,只不过需要安装一个模块,参考文档:http://pyyaml.org/wiki/PyYAMLDocumentation 常用模块之Co ...

  10. Python之xml文档及配置文件处理(ElementTree模块、ConfigParser模块)

    本节内容 前言 XML处理模块 ConfigParser/configparser模块 总结 一.前言 我们在<中我们描述了Python数据持久化的大体概念和基本处理方式,通过这些知识点我们已经 ...

随机推荐

  1. windows下使用IIS创建git服务

    Bonobo Git Server 下载地址: https://bonobogitserver.com/ 安装方法:https://bonobogitserver.com/install/ 配置简单, ...

  2. 我的Android进阶之旅------>android中一些特殊字符(如:←↑→↓等箭头符号)的Unicode码值

    在项目中,有时候在一些控件(如Button.TextView)中要添加一些符号,如下图所示:                         这个时候可以使用图片的方式来显示,不过这些可以直接使用Un ...

  3. Codeforces Round #245 (Div. 1)——Xor-tree

    版权声明:本文为博主原创文章,未经博主同意不得转载. https://blog.csdn.net/u012476429/article/details/25607945 题目链接 题意: 给一棵树n个 ...

  4. python2函数

    1.函数的定义 函数的定义形式如下: def <name>(arg1,arg2...argN): <statements> 函数的名字必须以字母开头,可以包括下划线.函数的目的 ...

  5. PHP基础学习代码案例

    <?php print 'hello world ! '; echo '<br/>'; ?> <?php $number="16"; $number2 ...

  6. python16_day16【Django_ORM、模板】

    一.ORM 1.MySQL配置 DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'books', #你 ...

  7. linux例行性工作调度学习(一)

    Linux系统中有一种例行性工作(crontab)可以调度,是通过crontab和at来实现的. 这两种工作调度: 一种是例行性的,就是每隔一定的周期要来办的事项. 一种是突发性的,就是这次做完以后就 ...

  8. Java 基础总结(二)

    本文参见:http://www.cnblogs.com/dolphin0520/category/361055.html 1. 字节流与和字符流 1). 字符流操作时使用了缓冲区,而在关闭字符流时会强 ...

  9. 动态背景的CSS3登录表单

    在线演示 本地下载

  10. 安装配置zabbix代理之zabbix_proxy

    配置Proxy代理 如图所示: zabbix_server端在阿里云上,其代理程序部署在各地机房,代理程序收集所在机房的所有机器监控指标,然后传给server端 环境说明: CentOS releas ...