yaml升级到5.3版本之后,使用yaml.load()会有警告信息。
YAMLLoadWarning: calling yaml.load() without Loader=... is deprecated, as the default Loader is unsafe. Please read https://msg.pyyaml.org/load for full details.
对于一个强迫症患者来说,是无法忍受的。先去官网看下到底是什么情况:
https://github.com/yaml/pyyaml/wiki/PyYAML-yaml.load(input)-Deprecation
在官网第一句就说了,这个页面解释了PyYAML 5.1 yaml.load(input)方法为什么不被推荐使用。yaml.load方法如果不指定Loader=...参数,是不被推荐的,如果直接使用yaml.load(input),虽然也可以用,但是会收到警告信息。在PyYAML 5.1以前的版本中,yaml.load是非常易于使用的,还举了个例子。
如何解决这个问题呢?有几种方式:
方式一:指定yaml.load(input, Loader=SafeLoader)
Loader有几种
①BaseLoader:仅加载最基本的YAML
②SafeLoader:安全地加载YAML语言的子集。建议加载不可信的输入。
③FullLoader:加载完整的YAML语言。避免执行任意代码。当前(PyYAML 5.1)是yaml.load(input)
(在发出警告之后)调用的默认加载程序。
④UnsafeLoader:不受信任的数据输入很容易利用的原始Loader代码。
with open(file=yamlPath, mode='r', encoding='utf-8') as f:
input = f.read()
s = yaml.load(input, Loader=yaml.SafeLoader)
print(s)
方式二:直接使用yaml.safe_load(input)
with open(file=yamlPath, mode='r', encoding='utf-8') as f:
input = f.read()
s = yaml.safe_load(input)
print(s)
方式三:全局禁用警告
with open(file=yamlPath, mode='r', encoding='utf-8') as f:
input = f.read()
yaml.warnings({'YAMLLoadWarning': False})
s = yaml.load(input)
print(s)