Systemmonitor process with shell_command

Hi there!
I am having some issues configuring a sensor.
Basically, I have a python script with an endless loop in it. I made a shell command in Home Assistant to launch it, and another one to kill the process.
Now I want to make a switch for activating and deactivating the script but I have no idea on how to consult the status of the script.
I tried with a systemmonitor of process type but I cannot make it work:

sensor:
  - platform: systemmonitor
    resources:
      - type: process
        arg: my_script.py

This did show it as always off. I belive it is because the process itself is /bin/sh -c python3 /some/route/my_script.py but I tried to use that as the arg value too and didn’t work either.
Any suggestions are appreciated.
Thanks!

What about a third script for the state.
Example:

#!/bin/bash

if ps x | grep -v grep | grep '/srv/ha/bin/python3.7 /srv/ha/bin/hass' >/dev/null; then
    exit 0
else
    exit 1
fi

It might do the job, but wouldn’t that just check if any python script is active? I would like to just check the actual script.
It’s a great idea though. I didn’t know about command line switches either. I’m going to tweak it a little and see if I can get what I need.

Thanks!

Modify it for your needs.

grep '/bin/sh -c python3 /some/route/my_script.py'
1 Like

BTW, you could also use the command only in the switch:

command_state: "ps x | grep -v grep | grep '/bin/sh -c python3 /some/route/my_script.py'"

but i prefer bash scripts, because you can change them without ha restart.

Thanks for the solution!
I finally ended using ps -ef | grep my_script.py | grep -v grep | wc -l and counting all the matching processes. Not that elegant solution but is more flexible, as it can find the script no matter where it is or what calls it.

2 Likes