run a python script in background and restart it on crash

5

8

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 ?

sebpiq

Posted 2012-08-14T14:19:14.550

Reputation: 153

For reference, exact same question was asked here: https://askubuntu.com/q/175751/753946

– PHPirate – 2019-03-28T17:36:52.990

As I just want the script to be running, isn't upstart enough ? Monit is needed only to make a test periodically right !? – sebpiq – 2012-08-14T14:28:23.433

Answers

9

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.

speakr

Posted 2012-08-14T14:19:14.550

Reputation: 3 379

1

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!

Neil Agarwal

Posted 2012-08-14T14:19:14.550

Reputation: 121

Completely unnecessary if the python script has the proper shebang. And this shebang will indicate the proper Python version.

– xenoid – 2017-06-22T11:49:48.083

And what if it doesn't? – Neil Agarwal – 2017-06-23T12:21:10.513

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. – Neil Agarwal – 2017-06-23T12:23:31.100

And what if it doesn't? Then you add one. – xenoid – 2017-06-23T13:40:38.710