背景
程序员在项目实战中,经常会遇到配置很多参数,如果直接写在程序当中,后续同事迭代开发会有很多弊端。例如,升级配置时如果配置参数是写在代码中,则需要更新整个代码,但是如果将常用的升级参数配置在易读易维护的配置文件中,则会省事很多...
常见的配置文件格式有两种:一种是ini格式文件,一种是json文件。这里介绍的是Python3内部自带的解析ini文件的configparser库。内容不难理解,请耐心阅读哦(建议电脑阅读)!
ConfigParser是什么?
配置文件解析器,Configration file parser,该模块实现了一种基础的配置语言类ConfigParser。这种语言类能够很方便的处理结构化的配置文件数据,该类定义实现在于Python的configparser.py文件中。
网址:https://docs.python.org/3/library/configparser.html
快速入门
首先,我们来看一下最基本的配置ini文件长什么样
[DEFAULT]name = 人工智能拾荒者age = 18good = yes[secret]beautiful = yes[area]city = BeiJingage = 100#Age = 200 key不区分大小写,因此多个age值会报错[Area]city = beijingage = 200[t1]city : BeijingAge : 300
对于ini文件的语法结构需要注意以下几点:- 键值对可以用 = 或者 : 进行分割
- section也就是文件中使用 [] 括起来的内容,区分大小写
- key不区分大小写的,value区分大小写
- 键值对中,头部和尾部的空白符会被自动去掉
- 配置文件可以有注释,注释使用# 或者
#coding=utf-8# 配置文件读取示例import configparserconfig = configparser.ConfigParser()print(config.sections()) # []config.read("ai.conf")print(config.sections()) # ['secret', 'area', 'Area', 't1']print(config) # if "DEFAULT" in config: print("yes") # yesif "area" in config: print("yes") # yesif "Area" in config: print("yes") # yesprint(config['area']['city']) # BeiJingprint(config['Area']['city']) # beijing
除了上述方法获取值之外,还可以使用section级别的get方法获取,同时该函数可以指定默认值。无论使用直接通过字典形式还是get方法获取,获取的数据都是字符串类型,如需获取指定类型的数据,可以使用getint()、getfloat()、getboolean()。
print(config['Area'].get('name','Jay')) # Area section没有name key,但是DEFAULT section有name # 所以优先使用默认section的默认值# 输出:人工智能拾荒者print(config['Area'].get('home','China'))# DEFAULT section没有home字段,因此使用默认值# 输出:China
程序构造配置文件
除了直接手写配置文件之外,还可以用程序构造,本节只需要了解即可,项目中使用较少。
#coding=utf-8import configparserconfig = configparser.ConfigParser()config['DEFAULT'] = { 'ServerAliveInterval': '45', 'Compression': 'yes', 'CompressionLevel': '9'}config['bitbucket.org'] = {}config['bitbucket.org']['User'] = 'hg'config['topsecret.server.com'] = {}topsecret = config['topsecret.server.com']topsecret['Port'] = '50022' # mutates the parsertopsecret['ForwardX11'] = 'no' # same hereconfig['DEFAULT']['ForwardX11'] = 'yes'with open('example.ini', 'w') as configfile: config.write(configfile)
[DEFAULT]serveraliveinterval = 45compression = yescompressionlevel = 9forwardx11 = yes[bitbucket.org]user = hg[topsecret.server.com]port = 50022forwardx11 = no