zl程序教程

您现在的位置是:首页 >  后端

当前栏目

python 配置文件管理模块configparser

Python模块配置文件 管理 configparser
2023-09-27 14:29:10 时间

example_test.ini:

[mysql]
host = 127.0.0.1
port = 3306
user = root
password = zhangjun.xue
database = id_info

configparser_test.py

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''=================================================
@Project -> File   :ais_auto_test_tools -> configparser_test
@IDE    :PyCharm
@Author :zhangjun.xue.o
@Date   :2019-08-15 18:29
@Desc   :
=================================================='''
import os
import configparser

# 项目路径
rootDir = os.path.split(os.path.realpath(__file__))[0]
print 'rootDir =                    ', rootDir
print 'os.path.realpath(__file__) = ', os.path.realpath(__file__)

# 获取当前文件所在的路径
current_dir = os.path.abspath(os.path.dirname(__file__))
print 'current_dir =                ', current_dir

# config.ini文件路径
configFilePath = os.path.join(rootDir, 'example_test.ini')


def get_config_values(section, option):
    """
    根据传入的section获取对应的value
    :param section: ini配置文件中用[]标识的内容
    :return:
    """
    config = configparser.ConfigParser()
    config.read(configFilePath)
    return config.get(section=section, option=option)


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


输出:


rootDir =                     /Users/xue_test
os.path.realpath(__file__) =  /Users/xue_test/configparser_test.py
current_dir =                 /Users/xue_test
result =                      3306

Process finished with exit code 0