【发布时间】:2019-03-08 21:01:06
【问题描述】:
我正在尝试实现如下 YAML 语法:
---
foo: bar
baz: buff
!Include: other/file
并让它在加载时由 PyYAML 处理,以便 other/file.yml 的内容:
---
special: value
与原始文件的内容合并,产生:
---
foo: bar
baz: buff
special: value
到目前为止,我已经关注 PyYAML Docs 和 Creating Custom Tag in PyYAML 并且能够获得一些尴尬的实现:
---
foo: bar
baz: buff
included: !Include other/file
翻译成:
---
foo: bar
baz: buff
included:
special: value
我看到在PyYAML Docs 中生成了顶级标签并且它可以工作(怪物)但是当我尝试走那条路线时我的代码失败了:
yaml.scanner.ScannerError: while scanning a simple key
in "sample.yml", line 4, column 1
could not find expected ':'
in "sample.yml", line 5, column 1
当前代码:
import yaml
import sys
from UserDict import UserDict
class Include(yaml.YAMLObject, UserDict):
yaml_tag = u'!Include'
def __init__(self, path):
self.path = path
data = {}
try:
with open(self.path+'.yml', 'r') as f:
data = yaml.load(f)
except IOError:
data = {}
self.data = data
def __str__(self):
return str(self.data)
def __repr__(self):
return "{0}(path={1})".format(self.__class__.__name__, self.path)
@classmethod
def from_yaml(cls, loader, node):
return Include(node.value).data
@classmethod
def to_yaml(cls, dumper, data):
return dumper.represent_scalar(cls.yaml_tag, data.path)
yaml.SafeLoader.add_constructor(u'!Include', Include.from_yaml)
yaml.add_constructor(u'!Include', Include.from_yaml)
# Required for safe_dump
yaml.SafeDumper.add_multi_representer(Include, Include.to_yaml)
yaml.add_multi_representer(Include, Include.to_yaml)
if __name__ == '__main__':
fname = sys.argv[1]
f = open(fname, 'r')
data = yaml.safe_load(f)
print("{0}".format(str(data)))
【问题讨论】: