在Pyyaml中,如何用块样式表示空字符串和列表?

时间:2012-06-04 13:44:37

标签: string yaml dump pyyaml empty-list

我为Any yaml libraries in Python that support dumping of long strings as block literals or folded blocks?中提到的折叠字符串,文字字符串添加了表示符。我还添加了representer来在转储的yaml内容中以块样式打印列表。

但问题是当字符串为空时,即“”或列表为空时,它们在转储的YAML内容中以非块样式出现。

如何强制pyyaml dumper输出“”带有“>”的空字符串或“|”生成的YAML内容中的块样式中的flow_style = False的样式和空列表?

1 个答案:

答案 0 :(得分:5)

经过一些研究,我可以使用Pyyaml将空字符串作为块文字('|>'中的样式)转储到YAML文件中。我的工作部分基于Any yaml libraries in Python that support dumping of long strings as block literals or folded blocks?

import yaml
from yaml.emitter import Emitter, ScalarAnalysis

class MyEmitter(Emitter):  
    def analyze_scalar(self, scalar):   
        # Empty scalar is a special case.
        # By default, pyyaml sets allow_block=False
        # I override this to set allow_block=True
        if not scalar:         
            return ScalarAnalysis(scalar=scalar, empty=True, multiline=False,
                allow_flow_plain=False, allow_block_plain=True,
                allow_single_quoted=True, allow_double_quoted=True,
                allow_block=True)   
        return super(MyEmitter, self).analyze_scalar(scalar)

# And I subclass MyDumper from MyEmitter and yaml.Dumper        
class MyDumper(yaml.Dumper, MyEmitter):
    pass
class folded_unicode(unicode): pass
class literal_unicode(unicode): pass

def folded_unicode_representer(dumper, data):
    return dumper.represent_scalar(u'tag:yaml.org,2002:str', data, style='>')
def literal_unicode_representer(dumper, data):
    return dumper.represent_scalar(u'tag:yaml.org,2002:str', data, style='|')

yaml.add_representer(folded_unicode, folded_unicode_representer)
yaml.add_representer(literal_unicode, literal_unicode_representer)

# I test it now
d = {'foo': {'folded': folded_unicode(''), 'literal': literal_unicode('')}}
print yaml.dump(d, Dumper=MyDumper)

输出:

foo:
  folded: >
  literal: |

但是,我无法找到以块样式转储空列表的方法。为此,我试图弄乱yaml / emitter.py,并意识到我需要一个非空列表以块样式转储它。

无论如何,这种努力并没有白费,而是非常令人兴奋:) 我希望有人可能觉得这很有用,或者可能有分享的东西。