使用字典的方式给python程序添加config信息

本文介绍了如何使用字典来管理Python程序的配置信息,通过创建一个类将字典内容转化为可读性强的对象。在`config.py`中定义配置字典,然后在`__init__.py`中实现字典到类的转换方法,最后在主程序`test.py`中加载并使用配置。这种方法使得参数配置更加灵活和易于操作。
摘要由CSDN通过智能技术生成

使用字典的方式给python程序添加config信息

1. 介绍

​ 对我来说,需要很多配置信息的python程序,主要是模型训练的脚本,需要设置batch_size等参数,本文记录一个比较好用的参数配置方法,利用了字典,并生成一个类。

2. 最简程序结构

├── configs
│   ├── config.py
│   └── __init__.py
└── test.py

3. 具体介绍

config.py中有一个字典,可以配置任意参数

cfg = dict(
    a=1,
    b=2,
    name='add',
)

__init__.py中包含将字典转为类的方法

import importlib

class cfg_dict(object):
    def __init__(self, d):
        self.__dict__ = d
        self.get = d.get

def set_cfg_from_file(cfg_path):
    spec = importlib.util.spec_from_file_location('cfg_file', cfg_path)
    cfg_file = importlib.util.module_from_spec(spec)
    spec_loader = spec.loader.exec_module(cfg_file)
    cfg = cfg_file.cfg
    return cfg_dict(cfg)

test.py中为主程序

import argparse
from configs import set_cfg_from_file

def parse_args():
    parse = argparse.ArgumentParser()
    parse.add_argument('--config', dest='config', type=str,
                       default='configs/config.py',)
    return parse.parse_args()

args = parse_args()
cfg = set_cfg_from_file(args.config)

print('a:{} and b:{} {} is {:.5f}'.format(cfg.a, cfg.b, cfg.name, cfg.a + cfg.b))

4. 运行

python test.py --config ./configs/config.py

输出如下:

a:1 and b:2 add is 3.00000
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值