首页 > 解决方案 > PyYAML 中 yaml.load 和 yaml.SafeLoader 的区别

问题描述

Python新手在这里。

我安装了 PyYAML 并尝试使用我在网上找到的这段代码来解析我收到的 YAML 文件。

import yaml

if __name__ == '__main__':
    try:
        foo = open("foo.txt","a+")
    except:
        print("Error in opening file.")

stream = open("s.yaml", 'r')
dictionary = yaml.load(stream)
#dictionary = yaml.SafeLoader(stream)
for key, value in dictionary.items():

    foo.write(key + " : " + str(value)+"\n")

然后我在输出中看到 yaml.load 由于安全问题而被弃用。所以我尝试使用 SafeLoader 来运行它。但这给了我错误

Traceback (most recent call last):
  File ".\parseYAML.py", line 11, in <module>
    for key, value in dictionary.items():
AttributeError: 'SafeLoader' object has no attribute 'items'

出于商业原因,我无法在此处发布实际数据文件,但有人对我如何让 SafeLoader 工作有任何提示吗?

标签: pythonyaml

解决方案


我们使用以下代码片段展示了一些使用 SafeLoader 的方法:(最后一行可能是您最感兴趣的,对于最简单的情况)

import yaml

env_variable_matcher = re.compile(r'<your custom pattern here>')

def env_variable_parser(loader, node):
    '''
    Parse a yaml value containing ${A-Z0-9_} as an environment variable
    '''
    ...
    return output

# Add support for yaml tag named env_var which matches a string containing
# an environment variable.  The environment variable will be replaced with its value
yaml.add_implicit_resolver('!env_var', env_variable_matcher, Loader=yaml.SafeLoader)
yaml.add_constructor('!env_var', env_variable_parser, Loader=yaml.SafeLoader)

with open(config_file, 'r') as c_file:
    config = yaml.safe_load(c_file)

推荐阅读