Score:1

How to auto-restart a Python script sometimes?

cn flag

I have a long running tool I’ve written. It, unfortunately, isn’t super reliable and sometimes crashes. I’ll call it myscript.py.

I run it with a launcher script called launch, which sets some env variables for my script.

Is there a way to run ./launch, but where if it crashes, it will automatically restart after two minutes, and if it crashes again, it will wait four minutes, and then if it crashes again, eight minutes, and so on, but it will never wait more than 64 minutes between retries?

Is there a command I can install that can do this restart functionality automatically? Alternatively, I’m open to a custom shell script or possibly doing it with a systemd service if that’s possible.

Score:0
jp flag

A Bash shell script:

#!/bin/bash

# Set initial wait in miutes
# ... It will be multiplied by 2 while the result is =< than "$limit"
min="2"
# Set maximum wait limit in minutes
limit="64"
# Set scrpt filename
name="myscript.py"

while sleep 5
  do
    if ! /bin/pgrep -f "$name" &> /dev/null
      then
        # Script is not running
        sleep "${min}m"
        [[ "$((min * 2))" -le "$limit" ]] && min="$((min * 2))"
        # Add your command to start the script/launcher on the next line
        # ... Send it to the background with "&" so the loop continues
        # example ---> /bin/bash /home/user/dir/launch &
        fi
    done

See more explanation and other ways here and here.

I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.