Automation: Help on Running Python script using Shell-Command

Hi,

So I’ve been trying to get an automation working which should delete old backups using Shell Commands. In order to achieve this from a docker environment I use a Python file to get this done but the automation wouldn’t run and gives me error 127. However the python script works when I manually run this.

Does anyone has an idea what I’m doing wrong?

Here below you can find all the information which should give a good look into the problem.

Thanks a lot in advance.!


Hardware: Raspberry Pi 4B
Home Assistant: running version 2023.3.5 on docker.
Python version: 3.7.3.
Python code name: delete_old_backups.py

import os
import time

backup_dir = "/home/pi/Configs/Home-Assistant/backups"
days_to_keep = 5

now = time.time()

for file in os.listdir(backup_dir):
    file_path = os.path.join(backup_dir, file)
    if os.path.isfile(file_path):
        if now - os.stat(file_path).st_mtime > (days_to_keep * 86400):
            os.remove(file_path)
            print("Deleted old backup:", file_path)```

Configuration.yaml file:
I’ve tried to run this with and without /usr/bin/ to see if it makes any difference but it doesn’t.

shell_command:
    delete_old_backups: "/usr/bin/python3 /home/pi/Configs/Home-Assistant/delete_old_backups.py"

Home Assistant Log files:

ERROR (MainThread) [homeassistant.components.shell_command] Error running command: `/usr/bin/python3 /home/pi/Configs/Home-Assistant/delete_old_backups.py`, return code: 127

A return code of 127 indicates that the command was not found. However if I log in and run the shell command, it does delete the old backups!

/usr/bin/python3 /home/pi/Configs/Home-Assistant/delete_old_backups.py
Deleted old backup: /home/pi/Configs/Home-Assistant/backups/90c03965.tar
Deleted old backup: /home/pi/Configs/Home-Assistant/backups/e6e3d371.tar

How do you create these backups?
Can HA inside the docker container access the /home/pi/… path?
Open a shell inside the HA container and test your script.

docker exec -it homeassistant bash
1 Like

Thanks @VDRainer:

The backups are created from HomeAssistant itself. They work just fine.

Very good point which I seem to forgot to check.
As per suggestion I run the script inside the docker and it didn’t work because of the path. So after adjusting the paths, I was able to run the script!

Many thanks for the extra pair of eyes, the link and your suggestion!!