Run python script when HA starts

I think I might have cracked this, based on posts here:

and some key documentation here:

GitHub - aio-libs/async-timeout: asyncio-compatible timeout class.

I am running HA OS on a mini PC, seems to work for this setup, not sure about others because I can’t test on setups I don’t have.

Objective: to run a python script (or scripts) every time HA starts and have the script carry on running in the background (I’m using two to collect process and log modbus data) without being terminated by Home Assassin.

Overview: create a new custom_component x_shell_command and modify it to remove the timeout, which uses async-timeout, which can be disabled by setting the timeout to None. From the above
github link: “timeout parameter could be None for skipping timeout functionality”. Then use x_shell_command with the time out removed instead of shell_command.

No doubt this will be seriously frowned upon, but if it works… I will of course keep an eye on things to see if it goes rogue.

Steps:

(1) create a folder in custom_components called ‘x_shell_command’

(2) download the three files __init__.py manifest.json and services.yaml from here (this is the HA core github) to your newly created ‘x_shell_command’ folder

(3) edit the manifest.json file so it looks like this:

{
  "domain": "x_shell_command",
  "name": "Shell Command (Extended)",
  "version": "1.0",
  "documentation": "https://www.home-assistant.io/integrations/shell_command",
  "codeowners": ["@home-assistant/core","@local"],
  "iot_class": "local_push"
}

(4) edit the __init__.py file lines 17 and 19 as follows:

DOMAIN = "x_shell_command"

COMMAND_TIMEOUT = None

(5) Add the following to the top of your python script. This (apparently) has the same effect as running ‘nohup … &’ on the command line (eg ‘nohup python myscript.py &’) ie no hangups allowed and run in background:

import os
import sys

os.fork() and sys.exit()

(6) Add the following to /config/configuration.yaml (you can add more than one entry as long as the have different names, and note that dot at the start of the path):

x_shell_command:
  run_myscript1: python ./pathto/myscript1.py
  run_myscript2: python ./pathto/myscript2.py

(7) Add the following to /config/automations.yaml:

alias: run_myscript
trigger:
  - platform: homeassistant
    event: start
condition: []
action:
  - service: x_shell_command.run_myscript1
  - service: x_shell_command.run_myscript2

(8) Stop the scripts if they are currently running (via terminal) and then check configuration (Developer Tools > YAML tab, correct if necessary but it should be OK) and if OK restart HA twice, the first time to load custom component x_shell_command, the second to trigger the actions.

I think that is it. The logic is simple enough for even me to follow it. Restart trigger > run custom x shell command action > start python script(s). Any comments welcome.