How can I stop execution of a python script on state change?

Hi All,

I have a python script that runs for a certain amount of time:
action:
- service: python_script.cycle_sirens

However, I need to stop its execution earlier if state of an entity changes:
- platform: state
entity_id: alarm_control_panel.house
from: ‘triggered’
action:

How can I do that? Tried
- service: homeassistant.turn_off
entity_id: python_script.cycle_sirens

but it does not work, and I can see nothing else that might do the job (home assistant.stop partially of work, but I don’t like the side effects :wink:

Any ideas?

You could put a condition into the script at various points to check if the state has changed. That way the script would stop. It will make your script longer but it should work.

For example,

condition:
  - condition: state
    entity_id: alarm_control_panel.house
    state: triggered

I was thinking about it, but please note mine script is a python script.
The trouble is I don’t know how to check the state of alarm_control_panel.house from python (basically - how to access that entity in the first place).
If I know that, it can be done (but I would prefer to be abel to kill the script to avoid hardcoding the entity_id).
Or maybe it’s possible to pass the entity’s name and then search by it… but I don’t know how to do it either, that’s my very first python script for HA, and I’m not very familiar with its internals.

Is this running with AppDaemon? Because if it is you can use http://appdaemon.readthedocs.io/en/stable/APPGUIDE.html#a-note-on-home-assistant-state to get the state. If it isn’t, you could use the REST api from home assistant to get the state.

I don’t know.
I created cycle_sirens.py in /config/python_scripts/ and have the following to run it in automations.yaml
action:
- service: python_script.cycle_sirens
entity_id: group.all_sirens

Found this in a search… but just in case, it’s pretty simple to get the state of any entity (states, attributes, etc.) are all avialable via the documented home assistant python api…

You can get the state of an entity by entity-id like this:

alarm_cp_state = hass.states.get("alarm_control_panel.house").state
logger.info("Alarm Control Panel State is: %s", alarm_cp_state)
1 Like