|
@@ -1,3 +1,94 @@
|
|
|
# omegaconf
|
|
|
|
|
|
-配置工具包,支持 YAML、JSON、INI
|
|
|
+配置工具包,支持 YAML、JSON、INI
|
|
|
+
|
|
|
+
|
|
|
+## Usage
|
|
|
+
|
|
|
+可以通过 pip 安装 OmegaConf:
|
|
|
+
|
|
|
+```
|
|
|
+pip install omegaconf
|
|
|
+```
|
|
|
+
|
|
|
+### 示例代码
|
|
|
+
|
|
|
+以下是一些 OmegaConf 的基本使用示例:
|
|
|
+
|
|
|
+#### 基本用法
|
|
|
+
|
|
|
+```
|
|
|
+from omegaconf import OmegaConf
|
|
|
+
|
|
|
+# 创建一个配置对象
|
|
|
+config = OmegaConf.create({
|
|
|
+ 'database': {
|
|
|
+ 'host': 'localhost',
|
|
|
+ 'port': 3306,
|
|
|
+ 'user': 'root',
|
|
|
+ 'password': 'password'
|
|
|
+ },
|
|
|
+ 'debug': True
|
|
|
+})
|
|
|
+
|
|
|
+# 访问配置项
|
|
|
+print(config.database.host) # 输出: localhost
|
|
|
+
|
|
|
+# 修改配置项
|
|
|
+config.database.port = 3307
|
|
|
+print(config.database.port) # 输出: 3307
|
|
|
+
|
|
|
+# 动态添加配置项
|
|
|
+config.database.name = 'mydatabase'
|
|
|
+print(config.database.name) # 输出: mydatabase
|
|
|
+```
|
|
|
+
|
|
|
+#### 从 YAML 文件加载配置
|
|
|
+
|
|
|
+```
|
|
|
+# config.yaml 文件内容
|
|
|
+"""
|
|
|
+database:
|
|
|
+ host: localhost
|
|
|
+ port: 3306
|
|
|
+ user: root
|
|
|
+ password: password
|
|
|
+debug: true
|
|
|
+"""
|
|
|
+
|
|
|
+from omegaconf import OmegaConf
|
|
|
+
|
|
|
+# 从 YAML 文件加载配置
|
|
|
+config = OmegaConf.load('config.yaml')
|
|
|
+
|
|
|
+# 访问配置项
|
|
|
+print(config.database.host) # 输出: localhost
|
|
|
+```
|
|
|
+
|
|
|
+#### 合并多个配置来源
|
|
|
+
|
|
|
+```
|
|
|
+from omegaconf import OmegaConf
|
|
|
+
|
|
|
+# 默认配置
|
|
|
+default_config = OmegaConf.create({
|
|
|
+ 'database': {
|
|
|
+ 'host': 'localhost',
|
|
|
+ 'port': 3306
|
|
|
+ }
|
|
|
+})
|
|
|
+
|
|
|
+# 用户配置
|
|
|
+user_config = OmegaConf.create({
|
|
|
+ 'database': {
|
|
|
+ 'port': 3307,
|
|
|
+ 'user': 'admin'
|
|
|
+ }
|
|
|
+})
|
|
|
+
|
|
|
+# 合并配置
|
|
|
+merged_config = OmegaConf.merge(default_config, user_config)
|
|
|
+print(merged_config.database.port) # 输出: 3307
|
|
|
+print(merged_config.database.user) # 输出: admin
|
|
|
+```
|
|
|
+
|