I wanted to print a YAML file (with keys and values) and with some values between double quotes. I wanted to use the solution provide here: How to print a value with double quotes and spaces in YAML?
Unfortunately when I installed ruamel.yaml for python 3.5 (sudo apt install python3-ruamel.yaml
) I was not able to find the function DoubleQuotedScalarString() in the script scalarstring.py .
Here is what it looks like:
from __future__ import absolute_import
from __future__ import print_function
__all__ = ["ScalarString", "PreservedScalarString"]
try:
from .compat import text_type
except (ImportError, ValueError): # for Jython
from ruamel.yaml.compat import text_type
class ScalarString(text_type):
def __new__(cls, *args, **kw):
return text_type.__new__(cls, *args, **kw)
class PreservedScalarString(ScalarString):
def __new__(cls, value):
return ScalarString.__new__(cls, value)
def preserve_literal(s):
return PreservedScalarString(s.replace('\r\n', '\n').replace('\r', '\n'))
def walk_tree(base):
"""
the routine here walks over a simple yaml tree (recursing in
dict values and list items) and converts strings that
have multiple lines to literal scalars
"""
from ruamel.yaml.compat import string_types
if isinstance(base, dict):
for k in base:
v = base[k]
if isinstance(v, string_types) and '\n' in v:
base[k] = preserve_literal(v)
else:
walk_tree(v)
elif isinstance(base, list):
for idx, elem in enumerate(base):
if isinstance(elem, string_types) and '\n' in elem:
print(elem)
base[idx] = preserve_literal(elem)
else:
walk_tree(elem)
Currently this is what I obtain when using ruamel.yamp.dump() to get my yaml file:
key1: 0,0,0,0
key2: 0,0,0,0
And here is what I would like in my yaml file:
key1: "0,0,0,0"
key2: "0,0,0,0"
How am I suppose to solve this?
The class DoubleQuotedScalarString
was added 2016-07-06.
You should update your version of ruamel.yaml
e.g. using pip install -U ruamel.yaml. You can see what version you have by looking at the __init__.py
in the yaml
directory. The current version (June 2018) has:
version_info=(0, 15, 37),
In general it is best not to install additional python packages under Linux, using the package manager. Instead create a virtualenv for each program you want to develop and install all packages necessary for that program in such a virtualenv.