一、簡介
configparser 是 Pyhton 標準庫中用來解析配置文件的模塊,並且內置方法和字典非常接近。
二、使用方法
1、定義配置文件
關於ini
配置文件的結構可以看python官方文檔中的介紹:
ini文件結構
ini文件結構需要注意一下幾點:
- 鍵值對可用=或者:進行分隔
- section的名字是區分大小寫的,而key的名字是不區分大小寫的
- 鍵值對中頭部和尾部的空白符會被去掉
- 值可以爲多行
- 配置文件可以包含註釋,註釋以#或者;爲前綴
[DEFAULT]
serveraliveinterval = 45
compression = yes
compressionlevel = 9
[bitbucket]
user = kk
[topsecrect]
port = 22
其中,[default] 、[bitbucket]等是section, 必須用"[ ]"。
下面,key-value組合是option, 可用"="或":" 分隔。
2、利用configparse類生成ini配置文件
類似python字典的方式來操作configparser類來生成配置文件
import configparser
config = configparser.ConfigParser()
config['DEFAULT'] = {'serveraliveinterval' : '4',
'compression' : 'yes',
'compressionlevel' : '9'}
config['bitbucket'] = {}
config['bitbucket']['user'] = 'kk'
config['topsecrect'] = {}
topsecrect = config['topsecrect']
topsecrect['port'] = '22'
with open('example.ini', 'w') as configfile:
config.write(configfile)
3、讀取配置文件
3.1單個值獲取
import os
import configparser
cur_path = os.path.dirname(os.path.realpath(__file__))
config_path = os.path.join(cur_path, 'config.ini')
conf = configparser.ConfigParser() # 注意大小寫
conf.read(config_path) # 配置文件的路徑
conf.get('mysql','host_name')
conf.getint('mysql','port')
.........
3.2封裝一個類獲取
import os
import configparser
class ConfigParser():
config_dic = {}
@classmethod
def get_config(cls, sector, item):
value = None
try:
value = cls.config_dic[sector][item]
except KeyError:
cf = configparser.ConfigParser() # 注意大小寫
cur_path = os.path.dirname(os.path.realpath(__file__))
config_path = os.path.join(cur_path, 'config.ini')
cf.read(config_path, encoding='utf8') # 注意config.ini配置文件的路徑
value = cf.get(sector, item)
cls.config_dic = value
finally:
return value
if __name__ == '__main__':
con = ConfigParser()
res = con.get_config('mysql', 'host_name')
print(res)
可見,生成的ini配置文件爲字符串類型構成的字典,所以使用get讀取數據的時候,也需要傳入字符串
參考:https://www.jianshu.com/p/61d139c6ea3d
https://www.jianshu.com/p/f393d3fbeebf
https://blog.csdn.net/weixin_42174361/article/details/82873878