2025年6月5日 星期四 乙巳(蛇)年 三月初九 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > Python

python通过configparser模块封装获取config.ini文件配置

时间:12-10来源:作者:点击数:13

python通过configparser模块封装获取config.ini文件配置

config.py: 

  • # 获取配置文件的内容
  • import os
  • import configparser
  • # configparser介绍: https://www.cdsy.xyz/computer/programme/Python/241210/cd64971.html
  • class Config(object):
  • def __init__(self, config_file='config.ini'):
  • # self._path = os.path.join(os.getcwd(), config_file)
  • self._path = os.path.join(os.path.dirname(__file__),config_file)
  • if not os.path.exists(self._path):
  • raise FileNotFoundError("No such file: %s" % config_file)
  • self._config = configparser.ConfigParser()
  • # 读取配置文件,返回confi.ini全路径地址,列表形式
  • self._config.read(self._path, encoding='utf-8-sig')
  • # 读取配置文件,返回confi.ini全路径地址,列表形式
  • self._configRaw = configparser.RawConfigParser()
  • self._configRaw.read(self._path, encoding='utf-8-sig')
  • def get(self, section, name):
  • return self._config.get(section, name)
  • def getRaw(self, section, name):
  • return self._configRaw.get(section, name)
  • global_config = Config()
  • if __name__ == '__main__':
  • print(global_config.getRaw('config','buy_time')) # 2021-01-08 09:59:59.500
  • print(global_config.getRaw('messenger','enable')) # false

config.ini文件大概内容:

  • [config]
  • buy_time = 2021-01-08 09:59:59.500
  • random_useragent = false
  • [messenger]
  • enable = false

其他文件引入:

  • from config import global_config
  • buy_time = global_config.getRaw('config', 'buy_time')
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门
本栏推荐