在python中读取YAML配置文件并使用变量 [英] Reading YAML config file in python and using variables

查看:1813
本文介绍了在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还可以指导您y将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配置文件并使用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆