Python PyYAML中yaml.load和yaml.SafeLoader之间的差异
这里是Python新手 我安装了PyYAML,并尝试使用我在网上发现的修改过的代码来解析我收到的YAML文件Python PyYAML中yaml.load和yaml.SafeLoader之间的差异,python,yaml,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
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'
回溯(最近一次呼叫最后一次):
文件“\parseYAML.py”,第11行,在
对于键,dictionary.items()中的值:
AttributeError:“SafeLoader”对象没有属性“items”
出于业务原因,我无法在此处发布实际数据文件,但有人对我如何让SafeLoader工作有任何提示吗?我们使用以下代码片段来展示使用SafeLoader的一些方法:(最简单的情况下,最后一行可能是您最感兴趣的部分)
导入yaml
环境变量匹配器=重新编译(r“”)
def env_变量_解析器(加载程序,节点):
'''
将包含${a-Z0-9}的yaml值作为环境变量进行分析
'''
...
返回输出
#添加对名为env_var的yaml标记的支持,该标记与包含
#环境变量。环境变量将替换为其值
yaml.add_implicit_解析器('!env_var',env_variable_matcher,Loader=yaml.SafeLoader)
add_构造函数('!env_var',env_variable_parser,Loader=yaml.SafeLoader)
打开(配置文件,'r')作为c_文件:
config=yaml.safe\u加载(c\u文件)
它应该是yaml.safe\u负载(流)
yaml.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)