Send python script result to sensor

I have a python script


import requests as req
import sys
import subprocess
from googleapiclient.errors import HttpError
from googleapiclient import sample_tools
from oauth2client.client import AccessTokenRefreshError

service, flags = sample_tools.init(
      "", 'analytics', 'v3', __doc__, __file__,

realtime ="ga:XXX",metrics="rt:activeUsers").execute()

print realtime

that gives back my Google Analytics Real Time Data, the result looks like that:

{u'kind': u'analytics#realtimeData', u'totalResults': 0, u'totalsForAllResults': {u'rt:activeUsers': u'0'}, u'columnHeaders': [{u'dataType': u'INTEGER', u'columnType': u'METRIC', u'name': u'rt:activeUsers'}], u'query': {u'metrics': [u'rt:activeUsers'], u'max-results': 1000, u'ids': u'ga:XXX'}, u'profileInfo': {u'webPropertyId': u'UA-XXX', u'internalWebPropertyId': u'XXX', u'tableId': u'realtime:XXX', u'profileId': u'XXX', u'profileName': u'Alle Websitedaten', u'accountId': u'XXX'}, u'id': u'', u'selfLink': u''}

Now I want to filter from this the value of u'totalResults': and send it to my Home Assistant server as a sensor

I tried

headers = {'x-ha-access': 'XXX', 'content-type': 'application/json'}
url = 'http://MYHASSIO:8123/api/states/sensor.google_real_time'
data = '{"state": "realtime"}'
response =, headers=headers, data=data)

but the sensor value is just ‘realtime’

What do I have to add in the python file that the totalResults value send to sensor.google_real_time?


Sorry, but it seems kind obvious… Your request set the state of the sensor to “realtime” not the value of realtime. You may want to do something like:

data = {"state": realtime['totalResults']}

Hi @clyra, thanks for your reply!

I changed it and added print (response.text) but I got this back:

{"message": "Invalid JSON specified."}

hm… just a problem formating the json string. Try this:

data = '{ "state": "' + str(realtime['totalResults']) + '" }'

its working! thank you very much!
One last question, I want to repeat that python script every 20 seconds, what do I have to add?

I want to run that python script in the background to get Real Time User from my website send to Home Assistant

Make a command line sensor , that excequte the script, set the scan_interval to 20