0

I want to make sure my python script is always running, 24/7. It's on a Linux server. If the script crashes I'll restart it via cron.

Is there any way to check whether or not it's running?

Alan Coromano
  • 24,958
  • 53
  • 135
  • 205
  • Why do not use supervisord ? – Ali SAID OMAR Feb 04 '16 at 13:28
  • There's nothing inherently wrong with, as Benjamin put it, "hacking this with a script", particularly if you are on a hand-rolled/light/embedded distro, but if you're on something mainstream, its best to learn existing facilities for the job. Which is probably systemd almost anywhere you go on an up-to-date distro, and about 5 different possibilities if an older distro needs to be supported. Also, this is more a superuser.com oriented question. – Brian McFarland Feb 04 '16 at 16:38

5 Answers5

3

Taken from this answer:

A bash script which starts your python script and restarts it if it didn't exit normally :

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

Then just start the monitor script in background:

nohup script_monitor.sh &

Edit for multiple scripts:

Monitor script:

cat script_monitor.sh
#!/bin/bash

until ./script1.py 
do
    echo "'script1.py' exited with code $?. Restarting..." >&2
    sleep 1
done &

until ./script2.py 
do
    echo "'script2.py' exited with code $?. Restarting..." >&2
    sleep 1
done & 

scripts example:

cat script1.py
#!/usr/bin/python
import time
while True:
    print 'script1 running'
    time.sleep(3)

cat script2.py
#!/usr/bin/python
import time
while True:
    print 'script2 running'
    time.sleep(3)

Then start the monitor script:

./script_monitor.sh

This starts one monitor script per python script in the background.

Community
  • 1
  • 1
FoamyBeer
  • 221
  • 5
  • 7
1

Try this and enter your script name.

ps aux | grep SCRIPT_NAME

Niklas Siefke
  • 343
  • 5
  • 13
1
  • Create a script (say check_process.sh) which will
    • Find the process id for your python script by using ps command. Save it in a variable say pid
    • Create an infinite loop. Inside it, search for your process. If found then sleep for 30 or 60 seconds and check again.
    • If pid not found, then exit the loop and send mail to your mail_id saying that process is not running.

Now call check_process.sh by a nohup so it will run in background continuously.

I implemented it way back and remember it worked fine.

Utsav
  • 7,914
  • 2
  • 17
  • 38
1

You can use

  • runit
  • supervisor
  • monit
  • systemd (i think)

Do not hack this with a script

Benjamin
  • 3,350
  • 4
  • 24
  • 49
1

upstart, on Ubuntu, will monitor your process and restart it if it crashes. I believe systemd will do that too. No need to reinvent this.

dsh
  • 12,037
  • 3
  • 33
  • 51