Can python script/app listen for state change?

Is this possible to have python script/application which can listen for state change from Home Assistant and take action? I know automation trigger within Home Assistant can do this (and I doing it for simple purpose) but I want some more complex logic to perform on certain event and also keep track of some local variables until next/future event(s).

I read documentation of “Python API” for Home Assistant but can’t figure it out. I see options to get state, set state, call services etc. but how about setting listener for state change of the entity?

I already have shell command line to trigger/call my custom python script but that goes out of scope (finishes the execution) and can’t have computed values stored until next time called on state change.

I tried using AppDeamon and I am struggling with the issue of not getting called my listener reliably each time of state change so trying to explore other options. It works for first few times but then not getting called.

I am new to Python and may not be aware of any other (simple/complex) possibilities.
Thanks in advance.

Perhaps if you shared what you are doing and the code you have we could figure out what the issue is?

@aimc, I will share more details on this with code snippet and behavior once I get back to home.
Appreciate your help.
Thanks

@aimc, I have posted the details of my issue where I am not getting called my entity state listener after getting called few times initially.
Here is the link to that post under third party integrations section as I believed that talks about the third party application AppDaemon. AppDaemon Q&A

Thanks a lot for your help