Race condition at startup between pyscript and automation

I have pyscript properly installed and running on my HA system, and have written a python script which runs without error and does what I intend.

I also have an automation that calls the python script under certain conditions.

When I reboot the system, the automation triggers and attempts to call the python script before pyscript has finished initializing, so HA flags this as an error, holding the automation off until I mark the issue as resolved.

Is there a way to get around this startup race condition?

It doesn’t appear that pyscript presents any properties that I can use as a condition in the automation.

I suppose I could create a helper Boolean that is forced to off at startup, and then gets set to on by an automation, but I don’t know what to use as a trigger for this automation aside from a fixed time delay…

Thanks for your help!

1 Like

Is your automation using the following trigger?

- platform: homeassistant
  event: start

I had a similar problem with an automation that triggered at startup and referenced a Template Binary Sensor (whose state wasn’t yet set correctly). I fixed the problem by changing the trigger to this:

- platform: event
  event_type: homeassistant_started

It triggers after various other things get loaded.

Good question, but no, the automation triggers off of the state of some helpers, which are restored during boot.

You gave me some ideas about using these startup events to set the state of a Boolean helper that would get used as a condition in my automation, but there appears to be a race condition between this and my automation as well.

In theory, this shouldn’t be necessary because the homeassistant_started event indicates all components have loaded and are ready for use.

It’s possible what you are observing isn’t due to what you suspect is the cause.

It’s possible what you are observing isn’t due to what you suspect is the cause.

Indeed, I think the issue is that pyscript is loaded, but it has not yet finished “compiling” the python script and has not yet added my service function to the system.

Pyscript does this dynamically when a script file changes. When I edit my .py file, the service function gets removed, then added back.

Is it possible to get HA to treat an entity as “temporary”, not persistent? If I could get HA to not restore the state of a helper or sensor entity, then I think I could devise a way to hold off my automation until the pyscript is done adding my script as a service.

You might want to reach out to pyscript’s author. Your situation can’t be unique so perhaps they already have a way of mitigating it.