Python3 configparser (配置解析)

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 节点内容
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容