• python配置文件读取


    在代码实现的过程中,我们经常选择将一些固定的参数值写入到一个单独的配置文件中。在python中读取配置文件官方提供了configParser方法。

    主要有如下方法(找官文):

     

    (这家伙很懒,直接复制官方文档尴尬)

    使用方法如下:

    import configparser
    config = configparser.ConfigParser()
    config.read(configFilePath)
    config.get(section=section, option=option)

    写的比较简单,详细使用可以查看python安装目录doc下面的官文。

    使用示例

    config.ini配置内容如下:

    [mysql]
    host = 127.0.0.1
    port = 3306
    user = root
    password = Zhsy08241128
    database = leartd
    

    现在假设我们要取出文件中的port值,实现过程为:

    # -*- coding:utf-8 -*-
    import os
    import configparser
    
    # 项目路径
    rootDir = os.path.split(os.path.realpath(__file__))[0]
    # config.ini文件路径
    configFilePath = os.path.join(rootDir, 'config.ini')
    
    
    def get_config_values(section, option):
        """
        根据传入的section获取对应的value
        :param section: ini配置文件中用[]标识的内容
        :return: 
        """
        config = configparser.ConfigParser()
        config.read(configFilePath)
        # return config.items(section=section)
        return config.get(section=section, option=option)
    
    
    if __name__ == '__main__':
        result = get_config_values('mysql', 'port')
        print(result)
    

      

  • 相关阅读:
    【SqlSugarCore】SqlSugarScope的异步上下文问题
    web系统国际化思路
    mac iterm2 报错“iterm2_precmd:type:50”解决
    Atcoder 123C 1, 2, 3
    Atcoder 123D Yet Another Sorting Problem
    Atcoder 124F Chance Meeting
    Atcoder 212D Querying Multiset
    Atcoder 212E Safety Journey
    Atcoder 212F Greedy Takahashi
    Atcoder 212G Power Pair
  • 原文地址:https://www.cnblogs.com/ianduin/p/8510353.html
Copyright © 2020-2023  润新知