run a python script in background and restart it on crash

21,968

Solution 1

Taken from this answer:

You could write a bash script monitor.sh which starts your python script and restarts it if it crashes but doesn't restart if the script exits normally:

#!/bin/bash
until myscript.py; do
    echo "'myscript.py' crashed with exit code $?. Restarting..." >&2
    sleep 1
done

Then just start the monitor script in background:

nohup monitor.sh &

As an alternative to nohup, you may also consider tmux or screen for running background processes.

Solution 2

The above answer is great. I can't comment as of now so maybe improve the answer here.

You might even want to write a function for "myscript" as it is a python script and not running under the bash env.

So,

#!/bin/bash

myscript(){
    python3 myscript [args..]
}

until myscript; do
    echo "'myscript' crashed with exit code $?. Restarting..." >&2
    sleep 1
done

New people to python or bash wouldn't know this small thing. Might help them. I used to struggle with such small stuff in the beginning. Do not want any others to!

Share:
21,968

Related videos on Youtube

sebpiq
Author by

sebpiq

Updated on September 18, 2022

Comments

  • sebpiq
    sebpiq almost 2 years

    I have a very simple Python script that I'd like to be always running on my ubuntu 12.04 server. I thought of using upstart + monit. Problem is that those tools seem rather complicated for a simple mortal like me, and I cannot find a simple example on the web.

    Is upstart + monit overkill ? / Does somebody know a simpler alternative ? / or a good tutorial ?

  • xenoid
    xenoid about 7 years
    Completely unnecessary if the python script has the proper shebang. And this shebang will indicate the proper Python version.
  • Neil Agarwal
    Neil Agarwal about 7 years
    And what if it doesn't?
  • Neil Agarwal
    Neil Agarwal about 7 years
    I post stuff sometimes in pretext of making newbies understand if their thing doesn't work. Everyone doesn't necessarily need to know what a shebang is.
  • xenoid
    xenoid about 7 years
    And what if it doesn't? Then you add one.