python configparser中默认值的设定方式

目录
  • configparser中默认值的设定
    • 解决方案
  • 使用configparser的注意事项
    • 注意要点

configparser中默认值的设定

在做某一个项目时,在读配置文件中,当出现配置文件中没有对应项目时,如果要设置默认值,以前的做法是如下的:

try:
    apple = config.get(section, 'apple')
except NoSectionError, NoOptionError:
    apple = None

但当存在很多配置时,这种写法太糟糕

幸好,在Configparser.get()函数中有一个vars()的参数,可以自定义;注:只能用ConfigParser.ConfigParser;rawconfigparser是不支持的

解决方案

1、定义函数:

class DefaultOption(dict):
    def __init__(self, config, section, **kv):
        self._config = config
        self._section = section
        dict.__init__(self, **kv)
    def items(self):
        _items = []
        for option in self:
            if not self._config.has_option(self._section, option):
                _items.append((option, self[option]))
            else:
                value_in_config = self._config.get(self._section, option)
                _items.append((option, value_in_config))
        return _items

2、使用

def read_config(section, location):
    config = configparser.ConfigParser()
    config.read(location)
    apple = config.get(section, 'apple',
                       vars=DefaultOption(config, section, apple=None))
    pear = config.get(section, 'pear',
                      vars=DefaultOption(config, section, pear=None))
    banana = config.get(section, 'banana',
                        vars=DefaultOption(config, section, banana=None))
    return apple, pear, banana

这样就很好解决了读取配置文件时没有option时自动取默认值,而不是用rasie的方式取默认值

此方案来之stackoverflow

使用configparser的注意事项

以这个非常简单的典型配置文件为例:

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

1、config parser 操作跟dict 类似,在数据存取方法基本一致

>> 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'

2、默认配置项[DEFAULT]section 的默认参数会作用于其他Sections

3、数据类型

  • config parsers 不会猜测或自动分析识别config.ini参数的数据类型,都会按照字符串类型存储,如果需要读取为其他数据类型,需要自定义转换。
  • 特殊bool值:对于常见的布尔值’yes’/‘no’, ‘on’/‘off’, ‘true’/‘false’ 和 ‘1’/‘0’,提供了getboolean()方法。

4、获取参数值方法 get()

  • 使用get()方法获取每一参数项的配置值。
  • 如果一般Sections 中参数在[DEFAULT]中也有设置,则get()到位[DEFAULT]中的参数值。

5、参数分隔符可以使用‘=’或‘:’(默认)

6、可以使用‘#’或‘;’(默认)添加备注或说明

[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?

7、写配置

常见做法:

config.write(open('example.ini', 'w'))

合理做法:

with open('example.ini', 'w') as configfile:
    config.write(configfile)

注意要点

1、ConfigParser 在get 时会自动过滤掉‘#’或‘;‘注释的行(内容);

  • 一般情况下我们手工会把配置中的暂时不需要的用‘#‘注释,问题在于,Configparser 在wirte的时候同file object行为一致,如果将注释’#‘的配置经过get后,再wirte到conf,那么’#‘的配置就会丢失。
  • 那么就需要一个策略或规则,配置需不需要手工编辑 ?还是建立复杂的对原生文本的处理的东西,我建议是管住手,避免将一些重要的配置爆露给用户编辑,切记行内注释和Section内注释。
  • 有一个相对简单的方法是:
  • 对单独在一行的代码,你可以在读入前把"#", ";"换成其他字符如’@’,或‘^’(在其bat等其他语言中用的注释符易于理解),使用allow_no_value选项,这样注释会被当成配置保存下来,处理后你再把“#”, ";"换回来。

2、在ConfigParser write之后,配置文本如果有大写字母’PRODUCT’会变为小写字母’product’,并不影响配置的正确读写。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • Python configparser模块应用过程解析

    一.configparser模块是什么 可以用来操作后缀为 .ini 的配置文件: python标准库(就是python自带的意思,无需安装) 二.configparser模块基本使用 2.1 读取 ini 配置文件 #存在 config.ini 配置文件,内容如下: [DEFAULT] excel_path = ../test_cases/case_data.xlsx log_path = ../logs/test.log log_level = 1 [email] user_name = 3

  • 详解Python利用configparser对配置文件进行读写操作

    简介 想写一个登录注册的demo,但是以前的demo数据都写在程序里面,每一关掉程序数据就没保存住.. 于是想着写到配置文件里好了 Python自身提供了一个Module - configparser,来进行对配置文件的读写 Configuration file parser. A configuration file consists of sections, lead by a "[section]" header, and followed by "name: valu

  • Python ConfigParser模块的使用示例

    前言 在做项目的时候一些配置文件都会写在settings配置文件中,今天在研究"州的先生"开源文档写作系统-MrDoc的时候,发现部分配置文件写在config.ini中,并利用configparser进行相关配置文件的读取及修改. 一.ConfigParser模块简介 该模块适用于配置文件的格式与windows ini文件类似,是用来读取配置文件的包.配置文件的格式如下:中括号"[ ]"内包含的为section.section 下面为类似于key-value 的配置

  • Python configparser模块操作代码实例

    1.生成配置文件 ''' 生成配置文件 ''' import configparser config = configparser.ConfigParser() # 初始化赋值 config["DEFAULT"] = {'ServerAliveInterval': '45', 'Compression': 'yes', 'CompressionLevel': '9'} # 追加 config['DEFAULT']['ForwardX11'] = 'yes' config['bitbuc

  • Python基于argparse与ConfigParser库进行入参解析与ini parser

    一.入参解析库 argparse 有时候写Python脚本,需要处理入参[-h][-v][-F]...等情况,如果自己来解析的话,会花费很多时间,而且也容易出问题,好在Python有现成的lib可以使用,就是argparse了,下面我们看看如何使用它. import argparse def get_version(): return "0.0.1" def cmd_handler(): args = argparse.ArgumentParser() args.add_argumen

  • Python如何使用ConfigParser读取配置文件

    在项目过程中,需要设置各种IP和端口号信息等,如果每次都在源程序中更改会很麻烦(因为每次都要重启项目重新加载配置信息),因此将需要修改的参数写在配置文件(或者数据库)中,每次只需修改配置文件,就可以实现同样的目的.Python 标准库的 ConfigParser 模块提供一套 API 来读取和操作配置文件.因此在程序开始位置要导入该模块,注意区分是python2还是python3,python3有一些改动 import ConfigParser #python 2.x import config

  • python configparser中默认值的设定方式

    目录 configparser中默认值的设定 解决方案 使用configparser的注意事项 注意要点 configparser中默认值的设定 在做某一个项目时,在读配置文件中,当出现配置文件中没有对应项目时,如果要设置默认值,以前的做法是如下的: try:     apple = config.get(section, 'apple') except NoSectionError, NoOptionError:     apple = None 但当存在很多配置时,这种写法太糟糕 幸好,在C

  • Angular中ng-options下拉数据默认值的设定方法

    今天学习了一下Angular中ng-options下拉数据默认值的设定方法,留个笔记 直接上代码 <div class="form-group"> <label class="col-sm-2 control-label">教师</label> <div class="col-sm-10"> <select style="display:block; width:100%; heig

  • Python使用函数默认值实现函数静态变量的方法

    本文实例展示了Python使用函数默认值实现函数静态变量的方法,具体方法如下: 一.Python函数默认值 Python函数默认值的使用可以在函数调用时写代码提供方便,很多时候我们只要使用默认值就可以了. 所以函数默认值在python中用到的很多,尤其是在类中间,类的初始化函数中一帮都会用到默认值. 使用类时能够方便的创建类,而不需要传递一堆参数. 只要在函数参数名后面加上 "=defalut_value",函数默认值就定义好了.有一个地方需要注意的是,有默认值的参数必须在函数参数列表

  • python 字典中取值的两种方法小结

    如下所示: a={'name':'tony','sex':'male'} 获得name的值的方式有两种 print a['name'],type(a['name']) print a.get('name'),type(a.get('name')) 发现这两个结果完全一致,并没有任何的差异. 怎么选择这两个不同的字典取值方式呢? 如果字典已知,我们可以任选一个,而当我们不确定字典中是否存在某个键时,我之前的做法如下 if 'age' in a.keys(): print a['age'] 因为不先

  • python函数指定默认值的实例讲解

    1.说明 (1)写函数时,可以为每个参数指定默认值.当调用函数为参数提供实际参数时,Python将使用指定的实际参数:否则,将使用参数的默认值.因此,给参数指定默认值后,可以在函数调用中省略相应的参数. (2)使用默认值可以简化函数调用,明确指出函数的典型用法. 2.实例 >>> def student(name, age=18): ... print('Hello, My name is ' + name + ', I am ' + str(age) + ' years old') .

  • jquery获取input type=text中的值的各种方式(总结)

     实例如下: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>JQuery获取文本框的值</title> <meta h

  • Python字典中的值为列表或字典的构造实例

    1.值为列表的构造实例 dic = {} dic.setdefault(key,[]).append(value) *********示例如下****** >>dic.setdefault('a',[]).append(1) >>dic.setdefault('a',[]).append(2) >>dic >>{'a': [1, 2]} 2.值为字典的构造实例 dic = {} dic.setdefault(key,{})[value] =1 *******

  • 关于el-select组件设置默认值的实现方式

    目录 el-select组件设置默认值问题 如何给el-select赋默认值 el-select组件设置默认值问题 最近写项目的时候遇到将el-select组件设置默认值需求,通过查阅资料发现很多是使用v-model来实现的,但是只用v-model可能会有一些小小的问题. 因此根据他们的进行改变了一下 实现方式 el-select组件:    <el-select v-model="templateValue" placeholder="请选择模板" @cha

  • mybatis-plus 插入修改配置默认值的实现方式

    目录 创建 插入修改默认值设置方法 mybatis-plus添加默认值 创建 插入修改默认值设置方法 @Component public class MetaObjectHandlerConfig implements MetaObjectHandler {       @Override     public void insertFill(MetaObject metaObject) {         Date currentDate = new Date();         //默认未

  • 深入讨论Python函数的参数的默认值所引发的问题的原因

    本文将介绍使用mutable对象作为Python函数参数默认值潜在的危害,以及其实现原理和设计目的 陷阱重现 我们就用实际的举例来演示我们今天所要讨论的主要内容. 下面一段代码定义了一个名为 generate_new_list_with 的函数.该函数的本意是在每次调用时都新建一个包含有给定 element 值的list.而实际运行结果如下: Python 2.7.9 (default, Dec 19 2014, 06:05:48) [GCC 4.2.1 Compatible Apple LLV

随机推荐