← 中文资源

简体中文版本

configparser 分层 INI 配置

用 configparser 多次 read_string 叠加默认层与环境覆盖层:后读的键覆盖先读的键,配置优先级显式可测,且不依赖文件系统。

阅读英文原文

实现说明

顶层就这几处状态:defaults、host、port、debug。

使用要点

  • 依赖检查:configparser——不是内建的,项目里必须有。
  • 每一步打印都带着自己的标签:host:、port:、debug:。

常见问题

运行之前需要装什么吗?

需要:configparser 必须在项目里,否则导入在加载时就会失败。

代码示例

import configparser

defaults = """
[server]
host = 127.0.0.1
port = 8000
debug = false
"""

production = """
[server]
host = 0.0.0.0
port = 8080
"""

config = configparser.ConfigParser()
config.read_string(defaults)
config.read_string(production)  # 后读的层覆盖同名的键

section = config['server']
print('host:', section['host'])
print('port:', section.getint('port'))
print('debug:', section.getboolean('debug'))
print('sections:', config.sections())
print('keys:', sorted(section.keys()))