Variables and their values are stored externally in a YAML file. How to read them as if I declare them internally?

huangapple go评论81阅读模式
英文:

Variables and their values are stored externally in a YAML file. How to read them as if I declare them internally?

问题

import yaml

with open("settings.yml", "r") as stream:
    try:
        data = yaml.safe_load(stream)
        setting1 = data["setting1"]
        setting2 = data["setting2"]
    except yaml.YAMLError as exc:
        print(exc)

print(setting1, setting2)
英文:

Instead of having to declare the variables and their values in the script, I would like to have them declared externally in a separate YAML file called settings.yml:

setting1: cat
setting2: dog

Is there a way to use the variables' names and values directly as if I declare them internally? E.g. running print(setting1, setting2) returns cat dog. So far I can only read it:

import yaml

with open("settings.yml", "r") as stream:
    try:
        data = yaml.safe_load(stream)
        for key, value in data.items():
            print(f"{key}: {value}")
    except yaml.YAMLError as exc:
        print(exc)

print(setting1, setting2)

The print(setting1, setting2) doesn't work. I take a look at the PyYAML documentation but am unable to find it.

答案1

得分: 1

我不确定你想做的是否是一个好主意,但可以通过分配给 globals() 来实现。

假设包含你的YAML文件的文档包含一个根级别的映射:

from pathlib import Path
import ruamel.yaml

file_in = Path('settings.yaml')

    
yaml = ruamel.yaml.YAML()
data = yaml.load(file_in)
for k, v in data.items():
    globals()[k] = v

print(setting1, setting2)

这将产生:

cat dog

官方建议的包含YAML文档的文件扩展名至少从2006年9月起是.yaml

英文:

I am not sure if what you want to do is a good idea, but it can be achieved by assigning to globals().
Assuming the document containing your YAML file contains a root level mapping:

from pathlib import Path
import ruamel.yaml

file_in = Path('settings.yaml')

    
yaml = ruamel.yaml.YAML()
data = yaml.load(file_in)
for k, v in data.items():
    globals()[k] = v

print(setting1, setting2)

which gives:

cat dog

The officially recommended extension for files containing YAML documents has been .yaml,
since at least September 2006

答案2

得分: 0

我明白了。以下是翻译好的部分:

"Stupid me. Instead of using YAML I just need to make it a module, e.g. settings.py. Then from settings import *. However if you have a canonical answer for YAML, I'll happy to accept it."

请注意,代码部分没有被翻译。

英文:

Stupid me. Instead of using YAML I just need to make it a module, e.g. settings.py. Then from settings import *. However if you have a canonical answer for YAML, I'll happy to accept it.

huangapple
  • 本文由 发表于 2023年5月28日 21:45:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/76351798.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定