Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

python - Can I control the formatting of multiline strings?

The following code:

from ruamel.yaml import YAML
import sys, textwrap

yaml = YAML()
yaml.default_flow_style = False
yaml.dump({
    'hello.py': textwrap.dedent("""
        import sys
        sys.stdout.write("hello world")
    """)
}, sys.stdout)

produces:

hello.py: "import sys
sys.stdout.write("hello world")
"

is there a way to make it produce:

hello.py: |
    import sys
    sys.stdout.write("hello world")

instead?

Versions:

python: 2.7.16 on Win10 (1903)
ruamel.ordereddict==0.4.14
ruamel.yaml==0.16.0
ruamel.yaml.clib==0.1.0
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...