If you load, then dump, your expected output, you'll see that ruamel.yaml
can actually
preserve the block style literal scalar.
import sys
import ruamel.yaml
yaml_str = """
hello.py: |
import sys
sys.stdout.write("hello world")
"""
yaml = ruamel.yaml.YAML()
data = yaml.load(yaml_str)
yaml.dump(data, sys.stdout)
as this gives again the loaded input:
hello.py: |
import sys
sys.stdout.write("hello world")
To find out how it does that you should inspect the type of your multi-line string:
print(type(data['hello.py']))
which prints:
<class 'ruamel.yaml.scalarstring.LiteralScalarString'>
and that should point you in the right direction:
from ruamel.yaml import YAML
from ruamel.yaml.scalarstring import LiteralScalarString
import sys, textwrap
def LS(s):
return LiteralScalarString(textwrap.dedent(s))
yaml = ruamel.yaml.YAML()
yaml.dump({
'hello.py': LS("""
import sys
sys.stdout.write("hello world")
""")
}, sys.stdout)
which also outputs what you want:
hello.py: |
import sys
sys.stdout.write("hello world")
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…