Evaluate a template from within a python_script?

I need to parse some JSON with a python script that I want to execute with the python_script service. The problem is that with the python_script service, you can’t use imports. I was thinking of using the from_json template filter and wondered if somehow I can evaluate a template from within the python script.

Anybody know if this is possible?

Pass the object to the script unmodified and it should be a dictionary

1 Like

Thanks! This worked beautifully. I didn’t realize that things were automatically parsed like that.

1 Like

Hello, I’m interested by the solution but I don’t understand how it’s done ?
What does mean : “Pass the object to the script unmodified and it should be a dictionary”

Is it something like :

service: python_script.script1
data:
  area_function: {{area_name}}

and in the script :

areaFunction = data.get("area_function")

I tried the code above, but it doesn’t work. I probably miss something. Do you have an example ?

Thank you :slight_smile:

  1. Put your template between quotes
  2. The template isn’t valid. If you want the value, do
service: python_script.script1
data:
  area_function: '{{ states("area_name") }}'

Ok thank you. I understand.
But I don’t want the value, I want using the function ‘area_name’ in a python script doing this :

areaFunction = data.get("area_function")
areaFunction('sensor.temperature')

The goal is, if I have “sensor.temperature” in area “Room1”, in my script I would like be able to do the code above and get “Room1” in the return “areaFunction(‘sensor.temperature’)”

I’m not sure if it’s possible :thinking:

What do you mean by that. Where would that “function” be defined?

Since the last version, you can use in template the function {{area_name(entity_id)}} to get the area name where the sensor is.
I wanted to use this in a python script. The title of this post was perfect, but I think the solution was not for me ^^

I now try to do the same I wanted to do, but with the script integration and not the python script. May be it will be easier.
Here is what I’m trying to do : How to retrieve the zone of a sensor in a script? - #7 by Ricounnet

Thanks for you help :+1:

1 Like