自动导入 YAML 变量?

Import YAML variables automatically?

我提供了以下代码。我只是想知道是否有更好、更简洁的方法将整个索引加载到变量中,而不是手动指定每个变量...

Python代码

script_dir = os.path.dirname(__file__)
file_path = os.path.join(script_dir, 'config.yaml')

with open(file_path, 'r') as stream:
    index = 'two'
    load = yaml.load(stream)
    USER = load[index]['USER']
    PASS = load[index]['PASS']
    HOST = load[index]['HOST']
    PORT = load[index]['PORT']
    ...

YAML 配置

one:
  USER: "john"
  PASS: "qwerty"
  HOST: "127.0.0.1"
  PORT: "20"
two:
  USER: "jane"
  PASS: "qwerty"
  HOST: "196.162.0.1"
  PORT: "80"

分配给 globals()

import yaml
import os

script_dir = os.path.dirname(__file__)
file_path = os.path.join(script_dir, 'config.yaml')

index = 'two'

with open(file_path, 'r') as stream:
    load = yaml.safe_load(stream)

for key in load[index]:
    globals()[str(key)] = load[index][key]

print(USER)
print(PORT)

这给出:

jane
80

一些注意事项:

  • 使用全局变量通常被认为是不好的做法
  • 正如 a p 在评论中指出的那样,这可能会导致问题,例如使用隐藏内置函数的键
  • 如果你必须使用 PyYAML,你应该使用 safe_load()
  • 您应该考虑使用 ruamel.yaml(免责声明:我是该软件包的作者),您可以在其中获得相同的结果:

    import ruamel.yaml
    yaml = ruamel.yaml.YAML(typ='safe')
    

    然后再次使用load = yaml.load(stream)(这是安全的)。