python 有个模块可以很方便地解析配置文件,这样我们就可以将配置写到单独的配置文件中而不是在主程序中还带上配置信息,模块分离,逻辑清晰。
安装 configparser :pip install configparser
常用的配置文件 .ini 的格式如下
[section1]
key1 = value1
key2 = value2
[section2]
key1 = value1
可以像字典一样操作 .ini 配置文件,对配置文件进行创建和修改
import configparser
config = configparser.ConfigParser()
#批量写入配置
config['DEFAULT'] = {
'db':'xiaohua',
'port':'18'
}
config['host1'] = {} #创建 section,必须先创建 section 才能在 section 下写入 key 和 value
config['host1']['db1'] = 'xiaoming' #创建 section 中的 key 和 value
config['host2'] = {}
config['host2']['db2'] = '5600'
sect = config['host2'] #将 section 赋给 sect
sect['port'] = '5601' #修改配置文件的内容
with open("example.ini",'w') as f: #打开文件
config.write(f) #配置文件写入打开的文件
最终得到的配置文件如下
对于 .ini 配置文件来说,section 就像字典的 key,section 下面的 key 和 value 就是字典形式的 key 的 value,也就是 {'section':{'key','value'}}
读取配置文件
需要注意的是实例化 configparser 对象后要读取配置文件才能对配置文件进行操作,并且 section 中的 key 都会保存为小写。
import configparser
config = configparser.ConfigParser()
print(config.sections())
print(config.read('example.ini')) #必须读入配置文件才能获得配置文件内容,之后便可以对配置文件进行操作(增删改查)
print(config.sections()) #获取配置文件的 sections,但是不会包含 default 这个 section(如果 default 大写的话)
print(config['DEFAULT']['db']) #读取 DEFAULT 这个 section 下 db 对应的值
for key in config['host2']:
print(key) #如果 default 大写的话会读到 default 下的第一个 key,因此推荐 default 小写避免未知错误,并且 section 中的 key 都会保存为小写
.ini 配置文件的 section 大小写敏感而 key 对大小写不敏感且都会保存为小写。另外,key 的值都会被处理成字符串,因此需要自己做类型转换。当然,configparse 也提供了 getint,getboolean 等方法对返回结果做转换。通用的获得值的方法是 get,跟 python 本身的 get 方法一样,get 允许在获取不到值的时候返回一个指定值。
import configparser
config = configparser.ConfigParser()
print(config.read('example.ini')) #必须读入配置文件才能获得配置文件内容,之后便可以对配置文件进行操作(增删改查)
print(config.get('host2','use')) #通过 config 对象的 get 方法获取值
sect = config['host2']
print(sect.get('hostname')) #通过 section 的 get 方法获取值,default 为所有的 section 提供了默认值
print(sect.get('name')) #返回 None
print(sect.get('name','no value'))
总结以上获取值的方法有一下几种:
1.利用 config 对象。直接 config['section']['key']
2.利用 section 对象。将 section 赋给变量再通过变量获取 key 的 value:sect = config['section'],sect['key']
该模块其他方法的使用也无外乎这 2 种,如 get 使用 config 调用 get 方法,需要传入 section 和 key 信息,如果使用 section 调用,就需要传入 key 信息。
ini 文件的一些事项
1.key 和 value 之间的分隔符可以是 ":" 或者 "="
[section]
key=value
key:value
2.key 和 value 都可以包含空格且 key 和 value 的开头和末尾的空格都会被忽略
[section]
k e y = va lue
3.value 都会被当作字符串对待
4.一个 key 的 value 可以有多个,只要其他的 value 比第一行的缩进更深
[section]
key = value1
value2
5.key 也可以没有值
[section]
key
key =
6.使用 "#" 或者 ";" 可以对 ini 配置文件进行注释
;comment
#comment
插值
class configparser.
BasicInterpolation
[path]
key1: value1
key2: %(key1)s/words #会被解析为 value1/words
key3: %(key2)s/Pictures #会被解析为 value1/words/Pictures
当 Interpolation 设为 None 时,key2 会被解析为 %(key1)s/words 而 key3 被解析为 %(key2)s/Pictures
class configparser.
ExtendedInterpolation
通过使用 ${section:key} 的方式可以获取其他 section 的值。
[Common]
home_dir: /Users
library_dir: /Library
system_dir: /System
macports_dir: /opt/local
[Frameworks]
Python: 3.2
path: ${Common:system_dir}/Library/Frameworks/
configparser 对象的其他方法及异常捕获:https://docs.python.org/zh-cn/3.7/library/configparser.html#supported-ini-file-structure
源码:https://github.com/python/cpython/blob/3.7/Lib/configparser.py