python configparser中默认值的设定方式
作者:Believer007 发布时间:2023-09-08 22:01:33
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’,并不影响配置的正确读写。
来源:https://www.cnblogs.com/landhu/p/9456095.html
猜你喜欢
- SQL Server导出表到EXCEL文件的存储过程:*--数据导出EXCEL导出表中的数据到Excel,包含字段名,文件为真正的Excel
- 本文实例为大家分享了JSP使用commons-fileupload实现文件上传代码,供大家参考,具体内容如下1、准备:将commons-fi
- 背景形态学处理方法是基于对二进制图像进行处理的,卷积核决定图像处理后的效果;形态学的处理哦本质上相当于对图像做前处理,提取出有用的特征,以便
- print函数的功能是打印图窗或保存为特定文件格式。语法print(filename,formattype)print(filename,f
- 编写思路:把本地文件在客户端通过base64编码以后发送目的地.测试过程中,上传文件过大,导致超时不成功,后来经过改善.把编码分
- 在网络设备管理中,传输配置文件、镜像文件等是经常需要进行的操作。Netmiko是一个Python库,可用于与各种网络设备进行交互,提供了一些
- SQL Server2005扩展函数已经不是一件什么新鲜的事了,但是我看网上的大部分都是说聚合函数,例子也比较浅,那么这里就讲讲我运用扩展函
- Python获取pid和进程名字1、安装psutilpip install psutil如果pip不识别,就进入下载的python目录下面执
- 目录查找算法 -- 简介顺序查找二分查找插值查找斐波那契查找树表查找1、二叉树查找算法。2、平衡查找树之2-3查找树(2-3 Tree)3、
- 在做task中,需要将TXT文本中的某一项注释修改,但是python对txt文本只有写入和读取两种操作。我采用的方法是:1.读取txt文件,
- 添加用户(随着用户的创建,自动产生与用户同名的schema) CREATE USER "TESTER" PROFILE
- 如下所示:def read_data(file_name): ''' file_name:文件地址 '
- 系列一:图片格式介绍Gif格式特点透明性Gif是一种布尔透明类型,既它可以是全透明,也可以是全不透明,但是它并没有半透明(alpha 透明)
- 谢谢icedblog提供的代码, 从那个js中我参考了moveSelect的利用, 不过那个代码中有几个BUG, 比如按住鼠标不放会不见显示
- <script>var d = '2013-07-21';var nd = d.replace(new RegE
- 1. 用SimpleITK读取dicom序列:import SimpleITK as sitkimport numpy as npimg_p
- 字符串中字符大小写的变换1. str.lower() //小写>>> 'SkatE'
- 最近接触了一些selenium模块的相关知识,觉得还挺有意思的,于是决定亲自尝试写一些爬虫程序来强化selenium模块(一定要多尝试、多动
- 本文实例为大家分享了python实现决策树的具体代码,供大家参考,具体内容如下算法优缺点:优点:计算复杂度不高,输出结果易于理解,对中间值缺
- 在Dreamweaver 4.0中,我们就已接触了模板与库的概念,知道它们是批量生成风格类似的网页的好工具。如今在Dreamweaver M