我有一个看起来像这样的YAML文件:
!!com.example.hero.YAMLAnimals
animals:
Land: [Cow, Lion]
Sea: [Salmon, Cod]
根据PyYAML文档,通过子类化YAMLAnimals
,我应该能够安全地加载yaml.YAMLOBJECT
对象。我尝试这样做:
class YAMLAnimals(yaml.YAMLObject):
yaml_tag = u'!com.example.hero.YAMLAnimals'
def __init__(self, animals):
self.animals = animals
但是,当我尝试使用yaml.load()
或yaml.safe_load()
解析文件时,出现以下错误:
could not determine a constructor for the tag 'tag:yaml.org,2002:com.example.hero.YAMLAnimals'
谢谢!
根据https://yaml.org/refcard.html,!!<name>
被视为辅助标签(按照惯例,是指tag:yaml.org,2002:<name>
)。因此,您应该将yaml_tag
中的YAMLAnimals
从u'!com.example.hero.YAMLAnimals'
更改为u'tag:yaml.org,2002:com.example.hero.YAMLAnimals'
,以便解析YAML文件中的!!com.example.hero.YAMLAnimals
标签。
也如@mgrollins所指出,您应将Loader
函数调用的yaml.load
指定为yaml.Loader
,作为当前问题的临时解决方法(https://github.com/yaml/pyyaml/issues/266)[https://github.com/yaml/pyyaml/issues/266]
test.yaml
!!com.example.hero.YAMLAnimals
animals:
Land: [Cow, Lion]
Sea: [Salmon, Cod]
Python代码:
import yaml
class YAMLAnimals(yaml.YAMLObject):
yaml_tag = u'tag:yaml.org,2002:com.example.hero.YAMLAnimals'
def __init__(self, animals):
self.animals = animals
stream = open('test.yaml', 'r')
data = yaml.load(stream, Loader=yaml.Loader)
stream.close()
print(data.animals)