Python3 configparser (配置解析)
时间:2019-05-18
环境:python3.7.3
官方文档:https://docs.python.org/3/library/configparser.html?highlight=configparser#configparser.ConfigParser
1. 相关模块引入
import configparser
2. 基础使用
conf.ini 配置文件:
import configparser
configPath = './conf.ini'
conf = configparser.ConfigParser()
## 写入
# conf['DEFAULT'] = {
# 'ServerAliveInterval': '45',
# 'Compression': 'yes',
# 'CompressionLevel': '9',
# 'ForwardX11': 'yes'
# }
# conf['MySQL'] = {
# 'host': 'localhost'
# 'port': '3306'
# 'username': 'root'
# }
# conf['domain.com'] = {
# 'Port': '50022',
# 'ForwardX11': 'no'
# }
# conf['DEFAULT']['ForwardX11'] = 'no'
# with open(configPath, 'w') as configfile:
# conf.write(configfile)
## 读取
conf.read(configPath)
print(conf.sections()) # ['MySQL', 'domain.com']
print('confItem' in conf) # False
print('DEFAULT' in conf) # True
print('MySQL' in conf) # True
print(conf.get('MySQL', 'host')) # localhost
print(int(conf['MySQL']['port']))
print('\n遍历 MySQL 节点 (同时遍历了 DEFAULT 的配置)')
for key in conf['MySQL']:
print(key + ' = ' + conf['MySQL'][key])
最终 conf.ini 配置文件内容:
[DEFAULT]
serveraliveinterval = 45
compression = yes
compressionlevel = 9
forwardx11 = no
[MySQL]
host = localhost
port = 3306
username = root
[domain.com]
port = 50022
forwardx11 = no
结论:
- 所有节点 包含 DEFAULT 节点内容
网友评论