Search code examples
pythonlinuxbashrestart

How to restart python script inside bash script every x hours?



I have a quite simple question about starting and restarting python scripts inside an bash script. I hope it's not an duplicate but I didn't find a similiar question.
I'm using a bash script which starts a couple of python scripts every time I create a docker container, but It should be probabaly the same on all linux based machines. It's simple as:

python3 /mnt/device/script.py &
Now the script will keep running and measure the brightness until the container is stopped. Now I figured out that there are some problems with the sensor library which are brightly discussed on github and still not solved which causes the script to stop every couple of hours. For me It would be enough to have just some command which restarts my script which is running in the background every x hours to avoid that error.
So what I'm looking for ist some command which will be like the follwing:

python3 for hour=1 /mnt/device/script.py restart &

Thanks in advance!


Solution

  • You can use the Bash timeout command to send a signal to kill the Python script.

    restart=""
    while true; do
        timeout 3600 python3 /mnt/device/script.py $restart
        restart="restart"
    done &
    

    I'm guessing you don't really need this to run in the background (so maybe take out the &) and that you literally want restart to be passed as an argument after the first time.