ConfigParser模块(py3中为configparser)主要被用来读写配置模块,这个模块定义了一个ConfigParser类,该类的作用是使用配置文件生效,配置文件的格式和windows的INI文件的格式相同。
格式
模块中有三种方法:
RawConfigParser()
ConfigParser()
SafeConfigParser()
这三个方法,创建一个对象使用对象的方法对指定的配置文件做增删改查操作。
配置文件有不同的片段组成和Linux中repo文件中的格式类似:
[section1]
name=value
[section2]
name: value
"#" 和";" 表示注释
[DEFAULT] #设置默认的变量值,初始化
在这,%(dir)s
会被frob
代替。
默认值会以字典的形式传递给ConfigParser的构造器。section一般存放的哦内置目录下,如果切换到其他的目录需啊哟指定存放位置。
[My Section]
foodir: %(dir)s/whatever
dir=frob
long: this value continues
in the next line
使用方法
下面这三种方式使用时,切记注意
在调用这三个函数时,切记这三个函数会将调用optionxform()
,在传递键值对数据时,会将键名 全部转化为小写。
RawConfigParser()
ConfigParser.RawConfigParser([defaults[, dict_type[, allow_no_value]]])
defaults : 如果指定默认值,则使用默认值的键值对
dict_type:使用新的section的键值对
allow_no_value :默认是False,如果是True,表示可以接收空值(None)
return:对象
不支持可变参数,在section中不能存在%()s
ConfigParser()
ConfigParser.ConfigParser([defaults[, dict_type[, allow_no_value]]])
在default中必须出现%()s
SafeConfigParser()
ConfigParser.SafeConfigParser([defaults[, dict_type[, allow_no_value]]])
更加智能化,在section中是否存在%()s会自动判断
传递参数使用函数optionxform(),foo %(bar)s 和 foo %(BAR)s是相同的,optionxform()会将大写字母全部转换为小写。
例子
写配置
import configparser
config = configparser.RawConfigParser()
config.add_section('Section1')
config.set('Section1', 'an_int', '15')
config.set('Section1', 'a_bool', 'true')
config.set('Section1', 'a_float', '3.1415')
config.set('Section1', 'baz', 'fun')
config.set('Section1', 'bar', 'Python')
config.set('Section1', 'foo', '%(bar)s is %(baz)s!')
# Writing our configuration file to 'example.conf'
with open('example.conf', 'wb') as configfile:
config.write(configfile)
读配置
import configparser
config = configparser.RawConfigParser()
config.read('example.cfg')
# getfloat() raises an exception if the value is not a float
# getint() and getboolean() also do this for their respective types
a_float = config.getfloat('Section1', 'a_float')
an_int = config.getint('Section1', 'an_int')
print(a_float + an_int)
# Notice that the next output does not interpolate '%(bar)s' or '%(baz)s'.
# This is because we are using a RawConfigParser().
if config.getboolean('Section1', 'a_bool'):
print(config.get('Section1', 'foo'))
获取插入值
import configparser
config = configparser.ConfigParser()
config.read('example.cfg')
# Set the third, optional argument of get to 1 if you wish to use raw mode.
print(config.get('Section1', 'foo', 0)) # -> "Python is fun!"
print(config.get('Section1', 'foo', 1)) # -> "%(bar)s is %(baz)s!"
# The optional fourth argument is a dict with members that will take
# precedence in interpolation.
print(config.get('Section1', 'foo', 0, {'bar': 'Documentation','baz': 'evil'}))
默认值
所有三种类型的config分析器都可以使用默认值。如果在其他地方没有定义一个选项,那么它们就被用于插值
import configparser
# New instance with 'bar' and 'baz' defaulting to 'Life' and 'hard' each
config = configparser.SafeConfigParser({'bar': 'Life', 'baz': 'hard'})
config.read('example.cfg')
print(config.get('Section1', 'foo')) # -> "Python is fun!"
config.remove_option('Section1', 'bar')
config.remove_option('Section1', 'baz')
print(config.get('Section1', 'foo')) # -> "Life is hard!"
在各section之间移动选项
def opt_move(config, section1, section2, option):
try:
config.set(section2, option, config.get(section1, option, 1))
except ConfigParser.NoSectionError:
# Create non-existent section
config.add_section(section2)
opt_move(config, section1, section2, option)
else:
config.remove_option(section1, option)
配置文件中有空值
>>> import ConfigParser
>>> import io
>>> sample_config = """
... [mysqld]
... user = mysql
... pid-file = /var/run/mysqld/mysqld.pid
... skip-external-locking
... old_passwords = 1
... skip-bdb
... skip-innodb
... """
>>> config = ConfigParser.RawConfigParser(allow_no_value=True)
>>> config.readfp(io.BytesIO(sample_config))
>>> # Settings with values are treated as before:
>>> config.get("mysqld", "user")
'mysql'
>>> # Settings without values provide None:
>>> config.get("mysqld", "skip-bdb")
>>> # Settings which aren't specified still raise an error:
>>> config.get("mysqld", "does-not-exist")
Traceback (most recent call last):
...
ConfigParser.NoOptionError: No option 'does-not-exist' in section: 'mysqld'
参考:
https://blog.csdn.net/sinat_38682860/article/details/99584037