在使用Python的过程中就会遇见配置环境参数的问题,今天学习了使用 configparser 模块来读取ini文件导入参数:
首先,创建一个config.ini文件:
[debug]
log_errors=true
show_warnings=False
[server]
port: 8080
nworkers: 32
pid-file=/tmp/spam.pid
root=/www/root
然后,在test模块去读取配置:
from configparser import ConfigParser
cfg = ConfigParser()
cfg.read('config.ini')
print(cfg.sections())
print(cfg.get('debug', 'log_errors'))
print(cfg.getint('server', 'port'))
#result:
['debug', 'server']
true
8080
FAQ:如果ini文件中有特殊符号%的时候使用ConfigParser这个办法就会报错
configparser.InterpolationSyntaxError: '%' must be followed by '%' or '(', found: '%v='
这时候就需要修改一下方法:
# cf = configparser.ConfigParser()
修改成
cf = configparser.RawConfigParser()
Python的ConfigParser Module中定义了3个类对INI文件进行操作。分别是RawConfigParser、ConfigParser、SafeConfigParser。RawCnfigParser是最基础的INI文件读取类,ConfigParser、SafeConfigParser支持对%(value)s变量的解析。