试图使用 pyyaml
来解析 mkdocs.yml
文件。它包含了一个这样的片段。
foo:
emoji_index: !!python/name:materialx.emoji.twemoji
当我运行..:
with open("test.yml", 'r') as stream:
try:
print(yaml.safe_load(stream))
except yaml.YAMLError as exc:
print(exc)
会出现以下错误:
could not determine a constructor for the tag 'tag:yaml.org,2002:python/name:materialx.emoji.twemoji'
in "test.yml", line 2, column 18
safe_load
限制了加载器只加载它知道的类型。这是因为加载任意类型会导致任意代码执行,这是一个安全风险。
为了正确加载文件,你有以下选项。
load
而不是 safe_load
并导入包含 materialx.emoji.twemoji
(我不知道这个定义在哪里,我在网上没有找到明确的答案)yaml.compose
. 这将返回YAML文档的根节点。这将不会直接把节点放入 dict
s, list
s等。def my_constructor(loader, node):
# since the content of the node is empty, you should return a value that
# can be used to identify the node, e.g.
return "materialx.emoji.twemoji"
yaml.add_constructor('tag:yaml.org,2002:python/name:materialx.emoji.twemoji',
my_constructor, yaml.SafeLoader)
哪种方法是最好的取决于你想对数据做什么。