Transform attribute in yaml.dump is not working

对着背影说爱祢 提交于 2021-02-11 12:15:28

问题


If we want to alter the output of yaml.dump we can use tranform keyword argument. Documentation: https://yaml.readthedocs.io/en/latest/example.html

Here is the yaml data:

metadata:
  name: name
  alias: alias

it is stored in variable x.

x = 'metadata:\n  name: name\n  alias: alias\n'

def tr(s):
    return s.replace('\n', '\n    ')  # Want 4 space at each new line

from ruamel.yaml import YAML
from ruamel.yaml.compat import StringIO

yaml = YAML(typ="safe")
yaml.default_flow_style = False
stream = StringIO()

obj = yaml.load(x)
yaml.dump(obj, stream, transform=tr)
print(stream.getvalue())

On running above python script, Got this error: TypeError: a bytes-like object is required, not 'str'

Expected output:

    metadata:
      name: name
      alias: alias

Note: Another 4 spaces are added in each line

Version Details of setup:

Python: 3.7
ruamel.yaml: 0.15.88

回答1:


Well I got the answer now. Have some problems with StringIO only, because YAML() always sets the encoding to utf-8 (and allow_unicode = True) Changing to use io doesn't bring anything. If you want to write to a StringIO in 2.7 you'll have to disable the utf-8 encoding:

i.e.

yaml = YAML(typ="safe")
yaml.default_flow_style = False
stream = StringIO()
yaml.encoding = None

For more info visit this ticket : https://sourceforge.net/p/ruamel-yaml/tickets/271/



来源:https://stackoverflow.com/questions/61228863/transform-attribute-in-yaml-dump-is-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!