Welcome, guest | Sign In | My Account | Store | Cart

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, 36 lines
 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)

4 comments

Nick Welch 14 years, 7 months ago  # | flag

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
Benjamin Sergeant (author) 14 years, 7 months ago  # | flag

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.

Nick Welch 14 years, 7 months ago  # | flag

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.

Benjamin Sergeant (author) 14 years, 7 months ago  # | flag

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 ...