pyyaml: dumping without tags

前端 未结 5 2002
囚心锁ツ
囚心锁ツ 2021-01-30 19:45

I have

>>> import yaml
>>> yaml.dump(u\'abc\')
\"!!python/unicode \'abc\'\\n\"

But I want

>>> import         


        
5条回答
  •  一个人的身影
    2021-01-30 20:25

    You need a new dumper class that does everything the standard Dumper class does but overrides the representers for str and unicode.

    from yaml.dumper import Dumper
    from yaml.representer import SafeRepresenter
    
    class KludgeDumper(Dumper):
       pass
    
    KludgeDumper.add_representer(str,
           SafeRepresenter.represent_str)
    
    KludgeDumper.add_representer(unicode,
            SafeRepresenter.represent_unicode)
    

    Which leads to

    >>> print yaml.dump([u'abc',u'abc\xe7'],Dumper=KludgeDumper)
    [abc, "abc\xE7"]
    
    >>> print yaml.dump([u'abc',u'abc\xe7'],Dumper=KludgeDumper,encoding=None)
    [abc, "abc\xE7"]
    

    Granted, I'm still stumped on how to keep this pretty.

    >>> print u'abc\xe7'
    abcç
    

    And it breaks a later yaml.load()

    >>> yy=yaml.load(yaml.dump(['abc','abc\xe7'],Dumper=KludgeDumper,encoding=None))
    >>> yy
    ['abc', 'abc\xe7']
    >>> print yy[1]
    abc�
    >>> print u'abc\xe7'
    abcç
    

提交回复
热议问题