Get status from a python script

What I would like to do is get the status of a python script that would be running on a separate device. The python script would have a value of 1 and 0. So if door is opened it would be 0 and if door was closed it would be 1. I would like it to show in home assistant has open or close.

There are a few different choices.

  1. Have the python script send updates periodically via Rest:
  1. Send updates to an MQTT server and then define that as a sensor in Home Assistant.

The second one is more complicated - especially if you don’t have an MQTT server running already. It’s what I do with a couple of custom scripts I have where I want to have data shared with HA.

Thanks, I’ll give it a try!

With python what do you recomend using to host a rest server as flask does not update if a variable updates?

Maybe I’m confused about what you’re trying to do. I think you have a python script that has a status that will change from time to time. I believe ou want to get that into HA. With the Restful call you have the python script send a JSON object to HA using a REST command. I’m not sure why you’d need a separate server for that.

If you’re trying to have the python script listen for a request and then send back the data, then you have to have a web server of some kind in the python script that will listen for that and send back a valid response. Then you would use the REST sensor type in HA to get that value. That’s a much more complex way to solve your problem IMHO.

So instead I get ha to send a post request to my python script?

If you’re going to have HA asking for the info, you can do it as a POST or a GET. It depends on how you setup the REST sensor:

I think i’m going to give up with this because I need to ask the python script for the data. I know how to make a get request from HA and put it into a senor. I just can’t get python to host a webserver with a variable that changes. As flask will not update the webserver if a variable changes.

Recently implemented what you describe I think. You could add a codeblock like this in your python script:

import json
import requests as req

    def message_ha(self):
        headers = {"Authorization": "Bearer -Bearer Key-"}
        url = "http://192.168.2.100:8123/api/states/sensor.any_name"
        data = {"state": json.dumps(any_string)}
        response = req.post(url, headers=headers, json=data)

Change the IP behind ‘url’ to your HA instance, also replace -Bearer Key- with your long lived token created in HA.

When you call message_ha() in your python script, it will automatically create a sensor in you HA instance and update it with the data you put into any_string. More info: REST API | Home Assistant Developer Docs