Reading YAML config file in python and using variables(在 python 中读取 YAML 配置文件并使用变量)
问题描述
假设我有一个 yaml 配置文件,例如:
Say I have a yaml config file such as:
test1:
minVolt: -1
maxVolt: 1
test2:
curr: 5
volt: 5
我可以使用以下方法将文件读入 python:
I can read the file into python using:
import yaml
with open("config.yaml", "r") as f:
config = yaml.load(f)
然后我可以使用
config['test1']['minVolt']
风格方面,使用配置文件中的变量的最佳方式是什么?我将在多个模块中使用变量.如果我只是简单地访问如上所示的变量,如果某些东西被重命名,我将需要重命名变量的每个实例.
Style-wise, what is the best way to use variables from the config file? I will be using the variables in multiple modules. If I simply access the variables as shown above, if something is renamed, I will need to rename every instance of the variable.
只是想知道在不同模块中使用配置文件中的变量的最佳或常见做法是什么.
Just wondering what the best or common practices for using variables from a config file in different modules.
推荐答案
你可以这样做:
class Test1Class:
def __init__(self, raw):
self.minVolt = raw['minVolt']
self.maxVolt = raw['maxVolt']
class Test2Class:
def __init__(self, raw):
self.curr = raw['curr']
self.volt = raw['volt']
class Config:
def __init__(self, raw):
self.test1 = Test1Class(raw['test1'])
self.test2 = Test2Class(raw['test2'])
config = Config(yaml.safe_load("""
test1:
minVolt: -1
maxVolt: 1
test2:
curr: 5
volt: 5
"""))
然后通过以下方式访问您的值:
And then access your values with:
config.test1.minVolt
重命名 YAML 文件中的值时,只需在一处更改类即可.
When you rename the values in the YAML file, you only need to change the classes at one place.
注意: PyYaml 还允许您直接将 YAML 反序列化为自定义类.但是,要使其正常工作,您需要向 YAML 文件添加标签,以便 PyYaml 知道要反序列化到哪些类.我希望您不想让 YAML 输入更复杂.
Note: PyYaml also allows you to directly deserialize YAML to custom classes. However, for that to work, you'd need to add tags to your YAML file so that PyYaml knows which classes to deserialize to. I expect that you do not want to make your YAML input more complex.
这篇关于在 python 中读取 YAML 配置文件并使用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 python 中读取 YAML 配置文件并使用变量


基础教程推荐
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 包装空间模型 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- 求两个直方图的卷积 2022-01-01