Cómo mantener un script en ejecución

tareas, procesos y sincronización
Instrucciones
El objetivo es montar un sistema que permita ejecutar un script Python sin interrupciones, independientemente de excepciones, reinicios o cualquier otro tipo de incidencia.

Esta solución se basa en definir un proceso cron que ejecuta un script (el que se adjunta) que determina si el script Python está ejecutándose y, en caso contrario, lo lanza de nuevo.
import sys
#Get the process id of this process
pid = os.getpid()
#Get the name of this script, as passed to the Python interpreter
myname = sys.argv[0]
#Run a ps command that includes the command lines of processes
ps = os.popen('ps --no-headers -elf|fgrep %s' % myname)
#Search for any processes that are running python and this script. We check for
#python so that we don't bomb when, for example, someone's editing this script
#in vi.
for p in ps:
if p.find('python')>-1 and p.find(myname)>-1:
#If the pid of the process we've found is not the same as our pid,

#then another instance is running.
otherpid = int(p.split()[3])
if otherpid <> pid: sys.exit()
ps.close()
Cŕeditos
Script desarrollado por Ben Last.
Notas Adicionales
Para más información consultar http://www.livejournal.com/users/benlast/21039.html.

Opciones de visualización de comentarios

Seleccione su manera preferida de mostrar los comentarios y haga click en 'Guardar opciones' para activar sus cambios.

Solución un poco menos chapucilla

Para no gastar recursos haciendos ps's (por cierto, mejor con el módulo commands.getoutput, en mi opinión) lo más lógico es hacer un fork(), ejecutar el programa que se quiere mantener y que el padre espere a que el proceso hijo termine (con wait() o como fuera, ahora no recuerdo bien.) Todo esto en un bucle, claro, para que cuando el proceso hijo termine se vuelva a crear otro.

En cualquier caso la mejor solución es no reinventar la rueda y usar un programa que haga exactamente esto y mucho más (hay varios en unix, run, daemon, etc.)

Lo siento pero después de ocho horas escribiendo Python en el curro no me apetece poner ejemplos de código ahora.