我提供了以下代码。我只是想知道是否有更好,更简洁的方法将整个索引加载到变量中,而不是手动指定每个索引...
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"
答案 0 :(得分:0)
致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
所述,这可能导致问题,例如使用阴影内置的键safe_load()
。您应该考虑使用ruamel.yaml
(免责声明:我是该软件包的作者),您可以在其中获得相同的结果:
import ruamel.yaml
yaml = ruamel.yaml.YAML(typ='safe')
然后再次使用load = yaml.load(stream)
(这是安全的)。