configparser
configparser模块能够配置和解析类似于windows系统下ini格式的文件,一个ini风格文件类似这样:
[section1] option = value option: value [section2] option = value option: value ...
它有两个概念section 和 option、value,理解起来很像python中字典的key和value.
很多应用都是通过配件文件来获取"配置", 这样很灵活。假设有类似这样的配置文件,可以用configparser模块去解析或配置它
[mysql] host = 192.168.127.210 port = 3306 db = learpython user = access passwd = access charset = utf8 [redis] host = 192.168.127.210 port = 6379 db = 0
基本用法
from configparser import ConfigParser
confing = ConfigParser()
confing = ConfigParser(strict=True) # 实例化
confing.optionxform = 'str' # 让option区分大小写confing.read('config.ini') # ['config.ini']
# 获取所有的section
confing.sections() # ['mysql', redis]
# 获取指定section中option-value
confing.items('mysql')
# [('host', '192.168.127.210'), ('port', '3306'), ('db', 'learpython'), ('user', 'access'), ('passwd', 'access'), ('charset', 'utf8')] confing.items('redis') # [('host', '192.168.127.210'), ('port', '6379'), ('db', '0')] dict(confing.items('redis'))
# {'host': '192.168.127.210', 'port': '6379', 'db': '0'}
# 获取指定section中所有的option
confing.options('mysql') # ['host', 'port', 'db', 'user', 'passwd', 'charset']
confing.options('redis') # ['host', 'port', 'db']
# 获取指定section的value,并且可以进行类型转换
confing.get('mysql', 'host') # 192.168.127.210
confing.getint('redis', 'port') # 6379 (int)
# 检查指定的section或section中的option是否存在
confing.has_section('mysql') # True
confing.has_section('db2') # False
confing.has_option('mysql', 'host') # True
confing.has_option('redis', 'hosts') # Fasle
添加、删除、设置指定的section或section中的option,然后写入配置文件
# 添加section
confing.add_section('oracle')
# 设置指定section中的option、value
confing.set('oracle', 'host', '192.16.1.203')
with open('config.ini', 'w') as f:
confing.write(f)
# 删除指定section中的option
confing.remove_option('oracle', 'host')
with open('config.ini', 'w') as f:
confing.write(f)
# 删除指定section confing.remove_section('oracle')
with open('config.ini', 'w') as f:
confing.write(f)
from configparser import ConfigParser import pymysql def mysql(): config = ConfigParser() config.read('config.ini') section = 'mysql' conf = { 'host': config.get(section, 'host'), 'port': config.getint(section, 'port'), 'user': config.get(section, 'user'), 'passwd': config.get(section, 'passwd'), 'db': config.get(section, 'db'), 'charset': config.get(section, 'charset') } conn = pymysql.connect(**conf) return conn
Interpolation of values
ConfigParser还支持interpolation(插值), 这意味着value可以在从get()调用返回之前进行预处理,有点像变量替换一样
# simple.ini [paths] home_dir: /Users my_dir: %(home_dir)s/lumberjack my_pictures: %(my_dir)s/Pictures
读取paths下的"my_pictures",
import configparser config = configparser.ConfigParser() config.read('simple.ini') print(config.get('paths', 'my_pictures')) # /Users/lumberjack/Pictures
ExtendedInterpolation
ExtendedInterpolation是Interpolation的扩展,使用ExtendedInterpolation可以使用跨section灵活的取值,更加灵活,有这样的ini 文件:
; settings.ini
[SectionOne] Param1: Hello Param2: World [SectionTwo] Param1: ${SectionOne:Param1} ${SectionOne:Param2} [SectionThree] Alpha: One Bravo: Two Charlie: ${Alpha} Mississippi
使用ExtendedInterpolation,这样可以更灵活的设置和解析section.
>>> from configparser import ConfigParser, ExtendedInterpolation >>> settings = ConfigParser(interpolation=ExtendedInterpolation()) >>> settings.read('settings.ini') ['settings.ini'] >>> settings.sections() ['SectionOne', 'SectionTwo', 'SectionThree'] >>> settings.get('SectionTwo', 'Param1') 'Hello World' >>> settings.get('SectionThree', 'Charlie') 'One Mississippi'
参考:
https://docs.python.org/3/library/configparser.html
https://wiki.python.org/moin/ConfigParserExamples
https://pymotw.com/3/configparser/