python - 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 工作有任何提示吗?
解决方案
我们使用以下代码片段展示了一些使用 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 - 用于 IOS 的带有 Objective-C 的 Python
- mysql - “错误”:“无法读取未定义的属性‘findOne’”
- android - React Native 下载和打开文件 - Android 上的文件是空白的
- ios - 框架在 Xcode 中是红色的,但构建时没有错误
- node.js - Heroku ReactJS 部署
- typescript - 扩展已知类的打字稿类型
- amazon-web-services - Aws EC2 Kubernetes 外部 IP 待定
- java - 在 OpenJDK 11.0.11 (JDK-8214213) 中更改了 jdeps 行为
- r - 如何“重新调整”R中data.frame列中的级别?
- php - 限制给定模型的多对多关系?