【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"])
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

BILLY BILLY

你的奖励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值