ActiveState Code

Recipe 576911: Keep a process up and running


If you have a long running process that can be killed for strange and unknown reason, you might want it to be restarted ... this script does that.

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#!/usr/bin/env python

import sys
import time
import subprocess

"""
Keep a process up and running

If you have a long running process that can be killed for strange and unknown
reason, you might want it to be restarted ... this script does that.

$ cat alive.sh 
#!/bin/sh

while `true`; do echo Alive && sleep 3 ; done

Use it like this:
$ keepup.py ./alive.sh 
"""

cmd = ' '.join(sys.argv[1:])

def start_subprocess():
    return subprocess.Popen(cmd, shell=True)

p = start_subprocess()

while True:
    
    res = p.poll()
    if res is not None:
        print p.pid, 'was killed, restarting it'
        p = start_subprocess()

    time.sleep(1)

Comments

  1. 1. At 3:12 p.m. on 23 sep 2009, mackstann Welch said:

    Curious, what's the point of this if you're already running something from a shell?

    while true; do cmd; echo "command was killed, restarting it"; done
    
  2. 2. At 3:18 p.m. on 23 sep 2009, Benjamin Sergeant (the author) said:

    The while true command is to demonstrate how this works.

    You can jump to another terminal and kill the ./alive.sh process, you will notice it is gonna be started again a few second later, and continue to see the "Alive" screen being printed in your terminal.

  3. 3. At 9:32 a.m. on 24 sep 2009, mackstann Welch said:

    Right, but this would still do the same thing, wouldn't it?

    while true; do ./alive.sh; echo "command was killed, restarting it"; done
    

    You could kill alive.sh and it would be restarted. It's just not clear to me why I would want to use 20 lines of python instead of one line of shell. I figured I might be missing the point... but maybe not.

  4. 4. At 7:59 a.m. on 7 oct 2009, Benjamin Sergeant (the author) said:

    I think you're right, it's the same feature :) Now you have to package your long line into a script (my python script is keepup.py), because it's a very long line to type ...

Sign in to comment