Python script using pexpect - unexpected behaviour


I have a rather strange issue:

I want to restart a systemd service through a shell_command, there is however something weird ongoing:

  1. If I switch to the homeassistant user, active the virtual environment, start a python session and copy/paste the commands of my script → everything works as expected and the systemd service restarts
  2. If I switch to the homeassistant user, active the virtual environment, and run the script as if the shell_command would do ‘python3 /home/homeassistant/.homeassistant/python_scripts/’ → behaviour is not the same aka the systemd service does not restart

Since 1) works, I imagine it’s not a permission issue. But I have no real idea how to debug this one. I’ve tried adding logmessages but they didn’t really indicate anything wrong.

The script is in essence below:

My installation of homeassistant is through dietpi (Home Automation Software Options - Docs)

  • Core 2024.2.1
  • Frontend 20240207.1
import pexpect
import logging

                            format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',
                            datefmt='%Y-%m-%d %H:%M:%S',

# import secret stuff, long-live token, hass ip address, sudo password
import headerfiles as parameters

child = pexpect.spawn('su -c "systemctl restart cassandra"')
# child.logfile = open("mylog", "wb")
# child.logfile = sys.stdout
child.expect('Password: ') #sudo password
logging.debug("password entered")
print(child.exitstatus, child.signalstatus)