Python中configParser模块的用法

2019-03-07  本文已影响0人  caoxinyiyi

configparser 简介

configparser 是 Pyhton 标准库中用来解析配置文件的模块,并且内置方法和字典非常接近。Python2.x 中名为 ConfigParser,3.x 已更名小写,并加入了一些新功能。目前我用的是Python2.x

configparser的使用

1、定义配置文件
[common]
search_pool = 1
first_screen_count = 6
is_contain_recommend = True

[mysql]
host_name = xxxx
user = xxxx
password = xxxx
db_name = xxxx
port = xxxx

其中,[common] 和[mysql]是section, 必须用"[]"。
下面key-value组合是option, 可用"="或":" 分隔。

2、获取配置文件的内容
import os
import configparser

cur_path = os.path.dirname(os.path.realpath(__file__))

config_path = os.path.join(cur_path, 'config.ini')

conf = configparser.ConfigParser()   #  注意大小写
conf.read(config_path)       # 配置文件的路径
conf.get('mysql','host_name')
conf.getint('mysql','port')
.........
import os
import configparser

class ConfigParser():
    config_dic = {}

    @classmethod
    def get_config(cls, sector, item):
        value = None
        try:
            value = cls.config_dic[sector][item]
        except KeyError:
            cf = configparser.ConfigParser()   #  注意大小写
            cur_path = os.path.dirname(os.path.realpath(__file__))
            config_path = os.path.join(cur_path, 'config.ini')
            cf.read(config_path, encoding='utf8')  # 注意config.ini配置文件的路径
            value = cf.get(sector, item)
            cls.config_dic = value
        finally:
            return value


if __name__ == '__main__':
    con = ConfigParser()
    res = con.get_config('mysql', 'host_name')
    print(res)

3、其它常用操作
# 获取所有 sections
config.sections()

# 获取指定 section 的 keys & values
 config.items('mysql')

# 获取指定 section 的 keys
config.options('mysql')

# 获取指定 key 的 value
config['mysql']['host_name']

# 添加
config.add_section('Section_1')

# 删除
config.remove_option('Section_1', 'key_1')

# 清空除[DEFAULT]之外所有内容
config.clear()

上一篇 下一篇

猜你喜欢

热点阅读