Using python scripts

Dear fellow HA users!

Recently i bought an Denon X2400H. I managed to setup an easy script to control the AVR with all the commands i received from Denon.

I wanted to use some automations which simply calls my python scripts/places input in the script. However to control the AVR i need to import some modules (socket for example).
Unfortunatly home-assistant is blocking me from doing this…

Are there work arounds? Other ways to use full python scripts?

Appdaemon allows you to use the full power of Python.
https://home-assistant.io/docs/ecosystem/appdaemon/

1 Like

Yeah i noticed but seemed it implied a learning curve. Made a workaround where i use shell commands to call functions in my script or parse arguments. Not the cleanest but works well atm.

Yes, but definitely worth it if you want to use Python for your automations.

1 Like

You can use command line component to call python like a shell script

@bbrendon Yeah thats what i ended up using. Still cant comprehend the reasoning behind not allowing the import function. When shell commands are avaliable the reason of security simply isnt availabe anymore.

I am in the prosess of doing the same for my Rotel.

Could you please post a sample code for the Shell command, where you call a function with argument in your Socket Python script.

This my shell command that calls a python script with an input.

shell_command:
  youtube: python3 /Users/ttt/.homeassistant/youtube.py --q="{{ search }}"

and I call it like this

intent_script:
  youtube:
    action:
      service: shell_command.youtube
      data_template:
        search: '{{ search }}'
1 Like

I think the preferred way to do this would be to make it a custom component and implement them as service calls. Custom components can specify REQUIREMENTS that will get installed during startup and can import whatever they need to use.

Thanks for responding!

I am a total N00b, but quite good at copy and paste, so if my function name with argument is RotelRemote(‘PowerOn’). And the file name is Rotel.py. How will the code be?

This is a simple python script that takes one input (an entity id) and turns it off. It might help.

import argparse
import requests
import simplejson as json


parser = argparse.ArgumentParser()
parser.add_argument("e")
args = parser.parse_args()


url = "http://192.168.2.186:8124/api/services/switch/turn_off"
data = {"entity_id": args.e}
headers = {'x-ha-access': 'password','Content-type': 'application/json'}
r = requests.post(url, data=json.dumps(data), headers=headers)

https://docs.python.org/3/library/argparse.html

So got my test script working when I use a function argument without space
But with space it throws an error. And I think it is the command line syntax.
image

How do I format the function argument with a space?
I want to use a space because I want to pick the argument in my script and make it an attribute in a HA-sensor.

My python script:

import socket
import sys

IPADDR = '192.168.1.251'
SERIALPORT = 4999
CONTROLPORT = 4998

def sendHex(code):
#    s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
#    try:
#      s.connect((IPADDR, SERIALPORT))
#    except socket.error as e:
#      print(e)     

#    s.send(bytes.fromhex(code))
#    s.close()
     print(code)


def Rotel_RSP1570_com(action):
    switcher = {
        'power Off' : 'FE 03 A3 10 4A 00',
        'powerOn'   : 'FE 03 A3 10 4B 01',
        'mute'      : 'FE 03 A3 10 1E D4',
        'volumUp'   : 'FE 03 A3 10 0B C1',
        'volumDown' : 'FE 03 A3 10 0C C2'
    }
    if switcher.get(action, 'Error') == "Error":
      print("Warning: Rotel RSP-1570 remote control - Invalid code: ", action)
    else:
      print(switcher.get(action, 'Invalid command'))    
      sendHex('YES!')

eval(sys.argv[1])

Can you use Power_Off or something and then replace the _ with a space in HA or in the python script?

After a lot off copy-and-paste research, all it took was double quotes for the function and argument.:smiley:

python C:\Users\Tom\Desktop\Python\x.py "Rotel_RSP1570_com('power Off')"

May I ask you what you do with that? Hehe I’m trying to autoplay the 1st video in youtube search depending on the media artist - title on my media player.

I used it for this.

Nice, exactly what I was looking for!

I do get that error tho :

Command executed: python3 /config/MP/pyton_scripts/youtube.py --q="{{ states.media_player.bose_soundtouch_petit.attributes.media_title  }}": 1
Traceback (most recent call last):
  File "/config/MP/pyton_scripts/youtube.py", line 1, in <module>
    from apiclient.discovery import build
ModuleNotFoundError: No module named 'apiclient' 

How do I load the missing module(s) on Hass.io running on RaspberryPi3 ?!
I think python3 is the good way to call python ion Hass.io ?

The process probably won’t work for you. I don’t use it mainly because for the media extractor to play youtube songs, it has to play youtube video. I use the VLC player on the pi, so I need to run HA from ssh console so that it can play the video. It plays it with text, kinda cool.

I don’t use Hass.io but I don’t think you can install programs. It appears you need to install apiclient. I would try this on a Pi with HA installed in a venv.

pip3 install apiclient

Okay thanks! I’ll scratch my head a little maybe I’ll think of something brilliant! haha