Python读取配置文件-ConfigParser的二次封装,简单好用
2017-03-30 23:22
597 查看
直接上上代码
test.conf
config.py
执行结果
目录结构
test.conf
[database] connect = mysql sleep = no test = yes
config.py
# -*- coding:utf-8 -*- __author__ = 'guoqianqian' import os import ConfigParser import os current_dir = os.path.abspath(os.path.dirname(__file__)) class OperationalError(Exception): """operation error.""" class Dictionary(dict): """ custom dict.""" def __getattr__(self, key): return self.get(key, None) __setattr__ = dict.__setitem__ __delattr__ = dict.__delitem__ class Config: def __init__(self, file_name="test", cfg=None): """ @param file_name: file name without extension. @param cfg: configuration file path. """ env = {} for key, value in os.environ.items(): if key.startswith("TEST_"): env[key] = value config = ConfigParser.ConfigParser(env) if cfg: config.read(cfg) else: config.read(os.path.join(current_dir, "conf", "%s.conf" % file_name)) for section in config.sections(): setattr(self, section, Dictionary()) for name, raw_value in config.items(section): try: # Ugly fix to avoid '0' and '1' to be parsed as a # boolean value. # We raise an exception to goto fail^w parse it # as integer. if config.get(section, name) in ["0", "1"]: raise ValueError value = config.getboolean(section, name) except ValueError: try: value = config.getint(section, name) except ValueError: value = config.get(section, name) setattr(getattr(self, section), name, value) def get(self, section): """Get option. @param section: section to fetch. @return: option value. """ try: return getattr(self, section) except AttributeError as e: raise OperationalError("Option %s is not found in " "configuration, error: %s" % (section, e)) if __name__ == "__main__": conf = Config() print conf.get("database").connect print conf.get("database").sleep print conf.get("database").test
执行结果
mysql False True
目录结构
demo conf test.conf config.py
相关文章推荐
- Python读取修改ini配置文件[ConfigParser]
- Python 读取写入配置文件 —— ConfigParser
- python3使用configparser读取带有中文的配置文件出现UnicodeDecodeError错误
- Python利用ConfigParser读取配置文件
- 【新手入门】Python下不喜欢使用ConfigParser去读取配置文件的Java developer
- Python 之 ConfigParser : 配置文件读取
- python-配置解析模块configparser-读取配置文件-遍历配置文件
- Python 读取写入配置文件 —— ConfigParser
- Python 读取写入配置文件 —— ConfigParser
- Python利用ConfigParser读取配置文件
- Python读取修改ini配置文件[ConfigParser]
- Python 封装读取CSV配置文件
- Python利用ConfigParser读取配置文件
- 详解Python读取配置文件模块ConfigParser
- Python的系统管理_11_ConfigParser读取配置文件
- Python+Selenium进行UI自动化测试项目中,常用的小技巧2:读取配置文件(configparser,.ini文件)
- python读取配置文件 ConfigParser
- paste deploy python ini 配置文件简单说明
- python中读取配置文件ConfigParser
- 读取配置文件生成简单的网站导航菜单