Python3 configparser (配置解析)
時間:2019-05-18
環(huán)境:python3.7.3
官方文檔:https://docs.python.org/3/library/configparser.html?highlight=configparser#configparser.ConfigParser
1. 相關(guān)模塊引入
import configparser
2. 基礎(chǔ)使用
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 節(jié)點 (同時遍歷了 DEFAULT 的配置)')
for key in conf['MySQL']:
print(key + ' = ' + conf['MySQL'][key])
最終 conf.ini 配置文件內(nèi)容:
[DEFAULT]
serveraliveinterval = 45
compression = yes
compressionlevel = 9
forwardx11 = no
[MySQL]
host = localhost
port = 3306
username = root
[domain.com]
port = 50022
forwardx11 = no
結(jié)論:
- 所有節(jié)點 包含 DEFAULT 節(jié)點內(nèi)容