【问题标题】:Import YAML variables automatically?自动导入 YAML 变量?
【发布时间】:2018-04-01 06:02:40
【问题描述】:

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

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"

【问题讨论】:

标签: python python-3.x yaml pyyaml


【解决方案1】:

Assing 到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)(这是安全的)。

【讨论】:

  • 请注意,这可能存在问题,因为它会影响内置函数以及 True 和 False 之类的东西。
  • 您的回答很有帮助!我也会检查你的包裹。感谢您的回复:)
猜你喜欢
  • 2021-02-07
  • 1970-01-01
  • 2016-11-04
  • 2021-12-19
  • 1970-01-01
  • 2021-01-08
  • 1970-01-01
  • 1970-01-01
  • 2015-05-11
相关资源
最近更新 更多