python之读写配置文件:config parser模块的用法

大本营:https://blog.csdn.net/HYZX_9987

项目结构(注意config的位置):

python之读写配置文件:config parser模块的用法_第1张图片

创建配置文件config.ini,内容自定,格式如下:

[url]
host = 127.0.0.1
port = 9010

[session]
macaronsession = 31de87b1019407f0

实现对配置文件增删改查的方法(方法名称即对应的功能):

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import os
import configparser
import logging

logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s: %(message)s',
                    filemode='w',
                    datefmt='%a, %d %b %Y %H:%M:%S')

# config目录的路径
rootDir = os.path.split(os.path.realpath(__file__))[0]
# config.ini文件路径
configFilePath = os.path.join(rootDir, 'config.ini')
logging.info('configfile-path:'+configFilePath)
config = configparser.ConfigParser()
config.read(configFilePath)

def get_config_values(section, key):
    """
    根据传入的section获取对应的value
    :param section: ini配置文件中用[]标识的内容
    :param key: ini配置文件中section下的指定的key
    :return: 要查的值
    """
    # config = configparser.ConfigParser()
    # config.read(configFilePath)
    # return config.items(section=section)
    if config.has_section(section):
        val = config.get(section=section, option=key)
        if val != None: logging.info('success to get config:['+section+'.'+key+']='+val)
    return val

def set_config_values(section,key,value):
    config.set(section,key,value)
    fh = open(configFilePath, 'w')
    config.write(fh)
    logging.info('success to set config: --> '+value)

def del_config_section(section):
    config.remove_section(section)
    fh = open(configFilePath, 'w')
    config.write(fh)
    logging.info('success to remove config: ' + section)

def del_config_sec_opt(section,option):
    config.remove_option(section, option)
    fh = open(configFilePath, 'w')
    config.write(fh)
    logging.info('success to remove config: ' + section + '.' + option)

# if __name__ == '__main__':
#     result = get_config_values('url', 'port')
#     print(result)

实例中调用:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

from config.configOps import *
from cpOps.entity import *
class CpClient:

    @staticmethod
    def getConfig(self,section, option):
        return get_config_values(section, option)

    @staticmethod
    def getConfigSession():
        return get_config_values('session', 'MacaronSession')

    @staticmethod
    def getConfigUrl():
        host =  get_config_values('url', 'host')
        port = get_config_values('url', 'port')
        return 'http://'+host+':'+port+'/api/v1/'

    @staticmethod
    def setConfig(section,key,value):
        set_config_values(section,key,value)

    @staticmethod
    def setConfigSession(value):
        set_config_values('session','MacaronSession',value)

    # @staticmethod
    def setConfigUrl(host,port):
        set_config_values('url', 'host', host)
        set_config_values('url', 'port', port)

    #删除 section 下全部
    @staticmethod
    def delSection(section):
        del_config_section(section)

    # 删除 section.option
    @staticmethod
    def delOpt(section,option):
        del_config_sec_opt(section,option)

#test success!
# cli = CpClient()
# cli.getConfigUrl()
# CpCli.setConfigSession('vvvvv')
# CpCli.setConfigUrl('127.0.0.1','9010')
# CpCli.delSection('haha')
# CpCli.delOpt('haha','ni')

 

 

你可能感兴趣的:(#,python)