Load shell color codes from YAML file

Viewed 713

How can i load a color code for my shell from a yaml file with ruamel yaml?##

I am able to change the color in my shell via python with some very simple instructions:

R = "\033[0;31;40m"
print(R+"TEST")

This outputs "TEST" in the color red. (I did not reset the style for simplicity)

I have the following YAML file:

colors:
  red : \033[0;31;40m

I try to achieve the same thing loading the color code from a YAML file, but it literally outputs \033[0;31;40mTEST. Here is my code. (I played around with different load types, quotes, escaping it, but I can't seem to get it working. I understand this happens for security reasons.)

import ruamel.yaml

path_to_config = "config/config.yml"

yaml = ruamel.yaml.YAML(typ="safe")

with open(path_to_inventory) as fpi:
    config = yaml.load(fpi)

print(config["colors"]["red"]+"TEST")
1 Answers

The backslash only has a special meaning in YAML if it is between double quotes. To know what your YAML should look like it is best to dump the result you want to have:

yaml.dump("\033[0;31;40m", sys.stdout)

gives:

"\e[0;31;40m"

So with:

colors:
  red : "\e[0;31;40m"

you should be fine.

The recommended extension for YAML files has been .yaml since 2007.

Related