python - 我可以控制多行字符串的格式吗?

标签 python yaml ruamel.yaml

以下代码:

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)

产生:

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

有没有办法让它产生:

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

代替?

版本:

python: 2.7.16 on Win10 (1903)
ruamel.ordereddict==0.4.14
ruamel.yaml==0.16.0
ruamel.yaml.clib==0.1.0

最佳答案

如果你加载,然后转储,你的预期输出,你会看到 ruamel.yaml 实际上可以 保留 block 样式文字标量。

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)

因为这再次给出了加载的输入:

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

要了解它是如何工作的,您应该检查多行字符串的类型:

print(type(data['hello.py']))

打印:

<class 'ruamel.yaml.scalarstring.LiteralScalarString'>

这应该会为您指明正确的方向:

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)

它也输出你想要的:

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

关于python - 我可以控制多行字符串的格式吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57382525/

相关文章:

python - 类型错误 : can't pickle generator objects wihen using mapPartitions

python - 使用 Matplotlib 缩放直方图上的第二个轴

yaml - sphinx 配置 ||配置/sphinx.yml

python - 为*未*通过 RoundTripLoader 加载的数据结构生成注释?

python - ruamel.yaml 在 Ubuntu 容器构建中需要 python-dev

python - 循环和列表 - 为攻击奠定基础

python - 将多个正则表达式合并为一个 RE

go - 忽略 YAML 标签

java - application.yml 是否支持环境变量?

python - 如何为 ruamel.yaml 创建自定义 yaml 映射转储程序?