Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/elixir/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中读取YAML配置文件并使用变量_Python_Yaml_Config - Fatal编程技术网

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

在python中读取YAML配置文件并使用变量,python,yaml,config,Python,Yaml,Config,假设我有一个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'] 就风格而言,使用配置文件中的变量的最佳方式是什么?我将

假设我有一个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输入变得更复杂。

请参见

导入yaml
从芒奇进口芒奇菲
c=最大(f)yaml.安全荷载(…)
打印(c.test1.minVolt)
# -1
#或
f=开放(…)
c=从YAML(f)开始咀嚼

使用GUI界面时的另一个问题。我有一个带有配置设置的选项卡,用户可以在其中编辑配置文件。我可以覆盖yaml配置文件,但是当访问另一个模块中的变量时(在变量更新之后),该模块仍然使用原始值。只有退出GUI并重新启动程序后,它才会使用新值。这是为什么?我如何解决它?如果这个答案解决了您的问题,请将其标记为这样。如果您还有其他问题,请创建一个新问题,显示您的代码并描述您的问题,而不是在此处进行注释。