[Solved] Problem running python script from command line - what am i doing wrong?!?!

i’m trying to run a python script from within HASS (hassbian) using the command line switch.
the script runs ok from the terminal when i am running as the homeassistant user in an activated virtual environment. I have given 777 perms, and changed the owner and group to homeassistant.

sudo -u homeassistant -H -s
source /srv/homeassistant/bin/activate
(homeassistant) homeassistant@hassbian:~/.homeassistant/python_scripts $ python /home/homeassistant/.homeassistant/python_scripts/testosc.py

so that all works well…

in hass:

  - platform: command_line
    switches:
      testosc:
        command_on: 'python /home/homeassistant/.homeassistant/python_scripts/testosc.py'
        command_off: '' 

i just get ‘command failed’ in the log.

can anybody shed any light on this? i’ve tried putting firmer paths in, /bin/python, or /bin/python3, or /usr/bin/python etc, but still nothing.

any thoughts would be heartily appreciated!

to run a python script, you just call the service:

  service: python_script.testosc

If you want to teather it to an activate button, make a script that calls the python_script an it will show up with an activate button:

script:
  thepythonscript:
    alias: Python Script
    sequence:
      - service: python_script.testosc

I believe the command line switch will create a new shell, which will not have the virtual environment activated. If the script needs the virtual environment activated, then the command needs to activate it within the command line.

@gpbenton thanks for the info - i had already played around with adding the activation command in the command line switch, which hadn’t worked. A little knowledge is never quite enough… :wink:

@petro I had tried using the python script component, but it also didn’t work. i wondered if that was because it is sandboxed/limited…

i have solved the problem by adding the path to python (in the venv) to the start of the script, and at the start of the hass command. the hass command now looks like this:

  - platform: command_line
    switches:
      testosc:
        command_on: "/srv/homeassistant/bin/python /home/homeassistant/.homeassistant/python_scripts/testosc.py"
        command_off: ''  

and the py file opens with:

#!/srv/homeassistant/bin/python

i don’t know which one is, or if both are, required, but it works so i’m done with it!

thanks for the input :slight_smile:

2 Likes

I assumed you were trying to use the python_script component because you placed the file into the correct location as if you were trying to use the component.

It is limited. Ignore my advice if you aren’t trying to use that component.

i revisited the python_script component now that i’ve got the comms path working. the component still didn’t work :roll_eyes: