首页 > 解决方案 > Pyyaml unable to parse a yaml file containing an indented block (using | or >)

问题描述

I'm trying to write a python script to parse a yaml file that contains markdown contained in a block literal.

Simple python script:

import yaml

file = open('single-source.yaml')

documentation = yaml.load(file, Loader=yaml.FullLoader)

print(documentation)

it works great when parsing a simple Yaml file e.g.

---
product name: Azure big VM
product version: 1.0.0
Operating System: RHEL
disk type: premium ssd
location: uk-south

However, when I try to do it with a YAML file using a pipe to escape a block of markdown (as is needed for my usecase), such as:

---
product name: | Azure big VM
product version: 1.0.0
Operating System: RHEL
disk type: premium ssd
location: uk-south

It starts to throw a ton of trackback errors pointing at the pyyaml files in python directory, as shown below. It spits out about 8 of these for various files in the /yaml directory.

 File "script.py", line 5, in <module>
    documentation = yaml.load(file, Loader=yaml.FullLoader)   File "C:\Users\Ryan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\yaml\__init__.py", line 114, in load
    return loader.get_single_data()

Can anybody offer any advice or work arounds?

标签: pythonpython-3.xyamlpyyaml

解决方案


Well as you said yourself, the block scalar must be indented. So this is the correct syntax:

---
product name: |
  Azure big VM
product version: 1.0.0
Operating System: RHEL
disk type: premium ssd
location: uk-south

You can't have content in the header. You may want to use |- instead of | to trim the trailing newline.


推荐阅读