日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

使用字典的方式給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

欄目分類
最近更新