• python ConfigParser


    ConfigParse 作用是解析配置文件。

    配置文件格式如下

    [test1]
    num1: 10
    [test2]
    num1: 35

    配置文件两个概念section和option, 在这个例子中第一个section是

    [test1]
    num1: 10

    其中test1是section name, 而num1是option的name。ConfigParser同样是根据section和option来解析配置文件。

    使用ConfigParser

    import ConfigParser
    conf = ConfigParser.ConfigParser()
    

    解析对应的配置文件:

    提供了两个方法

    -read()

    -readfp()

    这两个函数都是读取配置文件内容,不同之处是read参数是文件,而readfp的参数是handle。

    conf.read("test.config")
    
    conf.readfp(open("test.config"))
    

    获取配置文件内容

    -get(section,option)

    -getinit(section, option)

    -getfloat(section, option)

    -getboolean(section, option)

    这应该是最经常用到的函数,从配置文件中获取对应数值。get获取对应数值,后面三个函数在get的基础上进行了数值的转换。

    conf.get('test1', 'num1')
    conf.getint('test2', 'num1')
    

     第一行返回的是字符串10,第二行返回的是数值35。其他两个函数同理。

    需要注意的是getboolean(section,option)虽然返回True/False,在配置文件中可以为on/off True/False yes/no。方便了开关的配置。

    其余的函数则是对section,option和item的显示和判断操作

    比如has_section, 判断在配置文件中是否包含这个section

    conf.has_section('test1')
    

    类似函数has_option(section, option), 判断section中是否包含option

    显示内容函数例

    例如函数sections,显示所有的section

    options, 显示一个section下所有的option

    items,以(option,value)的形式显示section下所以的数值,返回列表。

    >>> conf.items('test1')
    [('num1', '10')]
    >>> conf.sections()
    ['test1', 'test2']
    >>> conf.options('test2')
    ['num1']
    >>> 
    

    在ConfigParser中还有一类函数修改添加option,section然后写入到配置文件文档。

    在我看来这是一个使用频率很低的函数。在一般程序中很少使用到。所以这个地方就不做讲解。

  • 相关阅读:
    盒子模型
    flex布局
    less基本使用
    vue全局配置(引入全局方法样式、按需加载elementui)
    vue性能优化
    vue实现原理
    webapi读取配置文件内容
    命令行启动dotnet core项目
    Linux常用命令
    sqlserver数据库密码忘记了,如何重置?
  • 原文地址:https://www.cnblogs.com/felixwa/p/5882234.html
Copyright © 2020-2023  润新知