前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python项目实现配置统一管理的方法

python项目实现配置统一管理的方法

作者头像
用户1154259
发布2018-09-21 11:34:41
1.5K0
发布2018-09-21 11:34:41
举报

一个比较大的项目总是会涉及到很多的参数,最好的方法就是在一个地方统一管理这些参数。最近看了不少的python项目,总结了两种很有意思的配置管理方法。

第一种 基于easydict实现的配置管理

首先需要安装numpy、easydict以及yaml:

代码语言:javascript
复制
pip install numpy 
pip install easydict
pip install yaml

就可以了。

然后定义配置类config.py

代码语言:javascript
复制
import numpy as np
from easydict import EasyDict as edict
import yaml

# 创建dict
__C = edict()
cfg = __C

# 定义配置dict
__C.dev = edict()
__C.dev.name = 'dev-xingoo'
__C.dev.age = 20

__C.test = edict()
__C.test.name = 'test-xingoo'
__C.test.age = 30

# 内部方法,实现yaml配置文件到dict的合并
def _merge_a_into_b(a, b):
    """Merge config dictionary a into config dictionary b, clobbering the
    options in b whenever they are also specified in a.
    """
    if type(a) is not edict:
        return

    for k, v in a.items():
        # a must specify keys that are in b
        if k not in b:
            raise KeyError('{} is not a valid config key'.format(k))

        # the types must match, too
        old_type = type(b[k])
        if old_type is not type(v):
            if isinstance(b[k], np.ndarray):
                v = np.array(v, dtype=b[k].dtype)
            else:
                raise ValueError(('Type mismatch ({} vs. {}) '
                                'for config key: {}').format(type(b[k]),
                                                            type(v), k))

        # recursively merge dicts
        if type(v) is edict:
            try:
                _merge_a_into_b(a[k], b[k])
            except:
                print(('Error under config key: {}'.format(k)))
                raise
        else:
            b[k] = v
# 自动加载yaml文件
def cfg_from_file(filename):
    """Load a config file and merge it into the default options."""
    with open(filename, 'r', encoding='utf-8') as f:
        yaml_cfg = edict(yaml.load(f))

    _merge_a_into_b(yaml_cfg, __C)

使用的时候很简单,main.py

代码语言:javascript
复制
from config import cfg_from_file
from config import cfg

cfg_from_file('config.yml')
print(cfg.dev.name)
print(cfg.test.name)

同级目录下创建配置文件config.yaml

代码语言:javascript
复制
dev:
  name: xingoo-from-yml

输出:

代码语言:javascript
复制
xingoo-from-yml
test-xingoo

总结

这样的好处就是在任何的Python文件中只要from config import cfg就可以使用配置文件。

第二种 基于Class实现

这种基于普通的python对象实现的,创建config2.py:

代码语言:javascript
复制
class Config:
    def __init__(self):
        self.name = 'xingoo-config2'
        self.age = 100

使用的时候直接创建一个新的对象,如何python模块之间需要引用这个变量,那么需要把配置对象传过去:

代码语言:javascript
复制
import config2 as config2

cfg2 = config2.Config()
print(cfg2.name)
print(cfg2.age)

输出为:

代码语言:javascript
复制
xingoo-config2
100

总结

第二种方法简单粗暴...不过每次传递参数也是很蛋疼。还是喜欢第一种方式。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-08-23 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 第一种 基于easydict实现的配置管理
    • 总结
    • 第二种 基于Class实现
      • 总结
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档