实现说明
顶层就这几处状态: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()))