假设我有一个 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,在 Python 中将 YAML 作为嵌套对象而不是字典加载
import yaml
from munch import munchify
c = munchify(f)yaml.safe_load(…))
print(c.test1.minVolt)
# -1
# Or
f = open(…)
c = Munch.fromYAML(f)
您可能想尝试 RecursiveNamespace 包。这篇文章提到了这一点。
https://stackoverflow.com/a/78504323/9538589
举个例子:
import yaml
from recursivenamespace import rns
datatext="""
test1:
minVolt: -1
maxVolt: 1
test2:
curr: 5
volt: 5
"""
# Load the YAML data
config_dict = yaml.safe_load(datatext)
# Convert to RecursiveNamespace
config = rns(config_dict)
print(config.test1.minVolt) # -1
print(config.test2.curr) # 5
# You can also access through keys
print(config['test1']['maxVolt']) # 1
# in versatile ways
print(config.test1['maxVolt'] is config['test1'].maxVolt) # True
# You can convert to dictionary
config_dict2 = config.to_dict()
print(config_dict == config_dict2) # True
# Or convert back to YAML (through dictionary)
config_yaml = yaml.dump(config.to_dict())
print(config_yaml)
# test1:
# maxVolt: 1
# minVolt: -1
# test2:
# curr: 5
# volt: 5