学无先后,达者为师

网站首页 编程语言 正文

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

作者:一路前行,幸运相伴 更新时间: 2022-10-11 编程语言

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

  • 1. 介绍
  • 2. 最简程序结构
  • 3. 具体介绍
  • 4. 运行

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

原文链接:https://blog.csdn.net/ShareProgress/article/details/126497483

栏目分类
最近更新