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.
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.
However, Python lacks built-in support for the YAML data format, commonly used for configuration and serialization, despite clear similarities between the two languages.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With