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')