是否可以在 YAML 中锚定文字块?

5 python yaml pyyaml

我正在做的是创建几个像下面这样的文字块,并将它们放在一个列表中。

literal1: |
    line
    of 
    text and stuff

literal2: |
    ...
Run Code Online (Sandbox Code Playgroud)

现在我无法弄清楚的部分是将它们列在列表中。我想我将使用锚点和别名,但它们似乎不适用于文字块。

这样做不起作用

literal1: | &literal1
    line
    of
    text and stuff
Run Code Online (Sandbox Code Playgroud)

它吐出一个错误。而且我宁愿不必创建一个字典

literals: &literal1
    literal1: |
        ....
Run Code Online (Sandbox Code Playgroud)

为了这个工作。我确信有一种简单的方法可以做到这一点,但我似乎无法找到它。

小智 6

这是你想做的吗?

literal1: &literal1 |
    line
    of 
    text and stuff

literal2: &literal2 |
    another line
    of text and new stuff

literals:
-  *literal1
-  *literal2    
Run Code Online (Sandbox Code Playgroud)

以下程序将打印...

['line\nof \ntext and stuff\n', 'another line\nof text and new stuff\n']

import yaml

data="""
literal1: &literal1 |
    line
    of 
    text and stuff

literal2: &literal2 |
    another line
    of text and new stuff

literals:
-  *literal1
-  *literal2    
"""

pydata = yaml.load(data)
literals = pydata [ 'literals' ]

print ( type(literals), literals )
Run Code Online (Sandbox Code Playgroud)

  • 我似乎找不到证据证明这是有效的 YAML 语法。我想使用 yaml 对 GitLab CI 作业做一些非常类似的事情,但这并没有通过验证器。 (2认同)