PyYAML variables in multiline

1.4k views Asked by At

I'm trying to get a multi-line comment to use variables in PyYAML but not sure if this is even possible.

So, in YAML, you can assign a variable like:

  current_host: &hostname myhost

But it doesn't seem to expand in the following:

test: |
    Hello, this is my string
    which is running on *hostname

Is this at all possible or am I going to have to use Python to parse it?

2

There are 2 answers

0
Anthon On BEST ANSWER

The anchors (&some_id) and references (*some_id) mechanism is essentially meant to provide the possibility to share complete nodes between parts of the tree representation that is a YAML text. This is e.g. necessary in order to have one and the same complex item (sequence/list resp. mapping/dict) that occurs in a list two times load as one and same item (instead of two copies with the same values).

So yes, you need to do the parsing in Python. You could start with the mechanism I provided in this answer and change the test

   if node.value and node.value.startswith(self.d['escape'])

to find the escape character in any place in the scalar and take appropriate action.

1
hajtos On

You can find the answer here.

Just use a + between lines and your strings need to be enclosed in 's.