The component provides the python_script.exec service, which allows you to run Python code in two ways:
- From a file: Use the
file parameter with a path relative to your configuration folder. Use cache: false to apply changes to the file without restarting Home Assistant. - From inline source: Use the
source parameter to paste Python code directly into your YAML.
Unlike the standard python_script component, you can import any library (provided they are in your requirements).
Available Variables in Scripts
When running via the service, the following variables are injected into your script:
hass: The Home Assistant API object.data: A dictionary containing the parameters passed to the service call.logger: A logger instance for message logging.
Starting from Home Assistant 2023.7, the service returns local script variables (with simple types) as a response.
# Example: Running a file
service: python_script.exec
data:
file: path_to/script.py
cache: false
param1: value1
# Example: Running inline source
service: python_script.exec
data:
source: |
import requests
r = requests.get('https://api.ipify.org?format=json')
logger.info(r.json())