python - PyYAML 中 yaml.load 和 yaml.SafeLoader 的区别

标签 python yaml

这里是 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 工作有任何提示吗?

最佳答案

我们使用以下代码片段来展示一些使用 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)

关于python - PyYAML 中 yaml.load 和 yaml.SafeLoader 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58434563/

相关文章:

python - md5 id批量导入数据到elasticsearch时出现UnicodeDecodeError

python - 使用欧拉角/矩阵在 3d 空间中旋转?

python - 应用 vs 嵌套 for 循环

spring-boot - 我可以从 Spring Boot 2 执行器集成中删除执行器字以进行健康检查吗

reactjs - Azure Devops react 脚本测试永远挂起

python - 当前缀存在时如何查找所有出现的情况

python - 存储和使用经过训练的神经网络

ruby to_yaml utf8 字符串

python - 试图让 dict 表现得像一个干净的类/方法结构

python - 在 yaml 中构建 Lambda 函数 - 问题