欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 房产 > 建筑 > 【mmengine】配置器(config)(入门)读取与使用

【mmengine】配置器(config)(入门)读取与使用

2024/10/26 9:30:51 来源:https://blog.csdn.net/m0_51579041/article/details/142656290  浏览:    关键词:【mmengine】配置器(config)(入门)读取与使用

一、 介绍

MMEngine 实现了抽象的配置类(Config),为用户提供统一的配置访问接口。
配置类能够支持不同格式的配置文件,包括 python,json,yaml,用户可以根据需求选择自己偏好的格式。
配置类提供了类似字典或者 Python 对象属性的访问接口,用户可以十分自然地进行配置字段的读取和修改。
为了方便算法框架管理配置文件,配置类也实现了一些特性,例如配置文件的字段继承等。

二、 配置文件读取

配置类提供了统一的接口 Config.fromfile(),来读取和解析配置文件。

  1. python格式配置文件:perfon_cfg.py
# Python 格式
name = "SHUAI"
addr = "Shanghai"
interest = ["food","travel"]
computer = dict(brand='dell', gpu="mx350")
  1. yaml格式配置文件:perfon_cfg.yaml
name: "SHUAI"
addr: "Shanghai"
interest:- food- travel
computer:brand: "dell"gpu: mx350
  1. json格式配置文件:perfon_cfg.json
{"name": "SHUAI","addr": "Shanghai","interest": ["food", "travel"],"computer": {"brand": "dell", "gpu": "mx350"}
}
  1. mmengine.config.Config.fromfile读取py,yaml,json三种格式的配置信息
from mmengine.config import Config# 从py中读取
import person_cfg as cfg_py
print(cfg_py.name)
print(cfg_py.addr)
print(cfg_py.interest)
print(cfg_py.computer)# 从yaml中读取
cfg_yaml = Config.fromfile('person_cfg.yaml')
print(cfg_yaml)# 从json中读取
cfg_json = Config.fromfile('person_cfg.json')
print(cfg_json)

在这里插入图片描述

三、 配置文件的使用

通过读取配置文件来初始化配置对象后,就可以像使用普通字典或者 Python 类一样来使用这个变量了。提供了两种访问接口,即类似字典的接口 cfg[‘key’] 或者类似 Python 对象属性的接口 cfg.key。这两种接口都支持读写。

### 使用 ###
print('------')
print(cfg_yaml.name)
print(cfg_yaml.addr)
print(cfg_yaml.interest)
print(cfg_yaml.computer)print('------')
print(cfg_json["name"])
print(cfg_json["addr"])
print(cfg_json["interest"])
print(cfg_json["computer"])

在这里插入图片描述

注意,配置文件中定义的嵌套字段(即类似字典的字段),在 Config 中会将其转化为 ConfigDict 类,该类继承了 Python 内置字典类型的全部接口,同时也支持以对象属性的方式访问数据。

附上完整代码:

# 1. person_cfg.py中代码
name = "SHUAI"
addr = "Shanghai"
interest = ["food","travel"]
computer = dict(brand='dell', gpu="mx350")
# 2. person_cfg.json中代码
{"name": "SHUAI","addr": "Shanghai","interest": ["food", "travel"],"computer": {"brand": "dell", "gpu": "mx350"}
}
# 3. person_cfg.yaml中代码
name: "SHUAI"
addr: "Shanghai"
interest:- food- travel
computer:brand: "dell"gpu: mx350# 4. config.py中代码
from mmengine.config import Config### 读取 ###
# 从py中读取
import person_cfg as cfg_py
print(cfg_py.name)
print(cfg_py.addr)
print(cfg_py.interest)
print(cfg_py.computer)# 从yaml中读取
cfg_yaml = Config.fromfile('person_cfg.yaml')
print(cfg_yaml)# 从json中读取
cfg_json = Config.fromfile('person_cfg.json')
print(cfg_json)### 使用 ###
print('------')
print(cfg_yaml.name)
print(cfg_yaml.addr)
print(cfg_yaml.interest)
print(cfg_yaml.computer)print('------')
print(cfg_json["name"])
print(cfg_json["addr"])
print(cfg_json["interest"])
print(cfg_json["computer"])

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com