Working example of comand_line sensor in hass.io w/o add-on or MQTT

According to this doc:
https://home-assistant.io/hassio/run_local/
The command_line platform for sensor should not work in hass.io
I recently moved from hassbian to hass.io and this example that extracts the amount of rainfall from a WEB site, to my amazement, still works!

In sensors.yaml:

  - platform: command_line
    name: Yesterday Rainfall
    unit_of_measurement: "mm"
    scan_interval: 10800
    command: "python3 /config/getrain.py"

In getrain.py:

!/usr/bin/python3.4

import urllib.request
import urllib.parse 
import re 
import xml.etree.ElementTree as ET 
from urllib import request 

#Now I can make the API call.  
id_request = urllib.request.urlopen('http://dd.weatheroffice.ec.gc.ca/citypage_weather/xml/BC/s0000141_e.xml')

#Let's now read this baby in XML format!
id_pubmed = id_request.read()
root = ET.fromstring(id_pubmed)

# Find the data I want
#elements are numbered with integers.  Uncomment to see order of elements
#for child in root:
	#print(child.tag,child.attrib)
#This is yesterday's rainfall in mm.
print(root[8][2].text)

This was a lot easier than the other methods offered in the above doc. No add-ons or MQTT involvement.
I was able to debug the python code in the IDLE environment on my Windows 10 PC and just copy it to the /config directory in hass.io

Have I found a security hole to get this working or just a simpler way to run a local python script?

1 Like

That’s brilliant!

Thanks a million for this, can confirm it works as a switch too!

- platform: command_line
  switches:
    mote_custom_switch_rgb:
      command_on: "python3 /config/mote-hass-api-call-for-hassio.py"
      command_off: "python3 /config/mote-hass-api-call-for-hassio.py"
      friendly_name: Illuminate

My python script has these imports:

#!/usr/bin/python3
from requests import get
import os

to run a curl command for me at the end:

os.system("curl -s " + break_slash.join( curl_string_sequence_join ))

All working a treat!

Does this approach still work with the current version of Hassio?

I am attempting something very similar but get the following error when the sensor is being setup:

Command failed: python3 /config/checkrental.py

jcasey,
Still works in hassio 0.69.1
Try a python program with only this single line:

print("Hello")

Your sensor should show “Hello” in the hassio frontend.

Don’t forget to make your python program executable:

chmod 755 python_program.py

If above works, then you have a bug in your python program. Solve this by testing your python program on a different system.

Thanks, was due to attempting to import urllib2 which worked find standalone but not within hassio. Switched to urllib and alls sorted!