且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在python中读取YAML配置文件并使用变量

更新时间:2022-12-05 22:22:18

您可以执行以下操作:

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.