Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute Python code embedded in YAML file

I'm wondering if it's possible to execute Python code that's embedded in a YAML file. For example, my YAML file currently contains a list:

list: [1,2,3,4]

But I'd prefer to enter this list in my YAML file using numpy:

list: np.arange(1,5)

I saw "How to embed Python code into YAML?" describing how to embed the Python code using literal scalar block style, but it doesn't describe how to actually execute the embedded code.

like image 921
Smed Avatar asked Sep 26 '14 14:09

Smed


People also ask

How do I automate a YAML file?

Automations are created in Home Assistant via the UI, but are stored in a YAML format. If you want to edit the YAML of an automation, go to edit the automation, click on the menu button in the top right and turn on YAML mode. The UI will write your automations to automations.

Does Python support YAML?

However, Python lacks built-in support for the YAML data format, commonly used for configuration and serialization, despite clear similarities between the two languages.


1 Answers

It is possible. The following Python script will do just that provided that your YAML file is named data.yml.

import yaml
with open("data.yml", "r") as f:
    data = yaml.load(f)
exec data['list']

Also make sure to add the imports in your Python code in the YAML file:

list: |
    import numpy as np
    print np.arange(1,5)
like image 106
Thomasleveil Avatar answered Sep 21 '22 06:09

Thomasleveil