Bash Script – How to Automatically Restart a Python Script if it Dies

bashcronpythonshell

I am running my Python script in the background in my Ubuntu machine (12.04) like this –

nohup python testing.py > test.out &

Now, it might be possible that at some stage my above Python script can die for whatever reason.

So I am thinking to have some sort of cron agent in bash shell script which can restart my above Python script automatically if it is killed for whatever reason.

Is this possible to do? If yes, then what's the best way to solve these kind of problem?

UPDATE:

After creating the testing.conf file like this –

chdir /tekooz
exec python testing.py
respawn

I ran below sudo command to start it but I cannot see that process running behind using ps ax?

root@bx13:/bezook# sudo start testing
testing start/running, process 27794
root@bx13:/bezook# ps ax | grep testing.py
27806 pts/3    S+     0:00 grep --color=auto testing.py

Any idea why px ax is not showing me anything? And how do I check whether my program is running or not?

This is my python script –

#!/usr/bin/python
while True:
    print "Hello World"
    time.sleep(5)

Best Answer

On Ubuntu (until 14.04, 16.04 and later use systemd) can use upstart to do so, better than a cron job. You put a config setup in /etc/init and make sure you specify respawn

It could be a minimal file /etc/init/testing.conf (edit as root):

chdir /your/base/directory
exec python testing.py
respawn

And you can test with /your/base/directory/testing.py:

from __future__ import print_function

import time

with open('/var/tmp/testing.log', 'a') as fp:
    print(time.time(), 'done', file=fp)
    time.sleep(3)

and start with:

sudo start testing

and follow what happens (in another window) with:

tail -f /var/tmp/testing.log

and stop with:

sudo stop testing

You can also add [start on][2] to have the command start on boot of the system.

Related Question