繁体   English   中英

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

[英]Reading YAML config file in python and using variables

假设我有一个 yaml 配置文件,例如:

test1:
    minVolt: -1
    maxVolt: 1
test2:
    curr: 5
    volt: 5

我可以使用以下命令将文件读入 python:

import yaml

with open("config.yaml", "r") as f:
    config = yaml.load(f)

然后我可以访问变量

config['test1']['minVolt']

在风格方面,使用配置文件中的变量的最佳方法是什么? 我将在多个模块中使用这些变量。 如果我简单地访问如上所示的变量,如果某些东西被重命名,我将需要重命名变量的每个实例。

只是想知道在不同模块中使用配置文件中的变量的最佳或常见做法是什么。

你可以这样做:

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
"""))

然后通过以下方式访问您的值:

config.test1.minVolt

当您重命名 YAML 文件中的值时,您只需在一处更改类。

注意: PyYaml 还允许您直接将 YAML 反序列化为自定义类。 但是,要使其正常工作,您需要向 YAML 文件添加标签,以便 PyYaml 知道要反序列化为哪些类。 我希望您不想让 YAML 输入变得更复杂。

参见Munch ,将YAML 加载为嵌套对象而不是 Python 中的字典

import yaml
from munch import munchify
c = munchify(f)yaml.safe_load(…))
print(c.test1.minVolt)
# -1
# Or
f = open(…)
c = Munch.fromYAML(f)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM