網站首頁 編程語言 正文
使用字典的方式給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
相關推薦
- 2024-01-31 nginx配置文件中最后一個 include servers/*;作用是什么?
- 2022-06-18 C#實現無損壓縮圖片代碼示例_C#教程
- 2022-04-03 Android?App應用退到后臺顯示通知的實現方法_Android
- 2023-04-19 Android開發服務Service全面講解_Android
- 2023-02-26 nvidia-smi命令詳解和一些高階技巧講解_linux shell
- 2022-12-04 Flutter之可滾動組件實例詳解_IOS
- 2022-10-27 使用python+pandas讀寫xlsx格式中的數據_python
- 2021-11-26 linux服務器磁盤空間擴充方法_Linux
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支