Azitech

Azimout's Linux weblog

Python Watchdog

with 2 comments

I wrote a Python script that needs to run continuously, read data from the serial port and make some calculations. I’ve added exception handling almost everywhere to make it skip bad data rather than crush. Still, every now and then it will encounter some error, raise an exception and exit. Therefore I set upon the task of implementing some sort of watchdog that would periodically check if my script is still running, and if not, launch it again.

I found various packages that do something similar, but not exactly what I need:

In the end, I found a way to implement this using the multiprocessing module:

import time, multiprocessing
import mydaemon

def abc():
    mydaemon.myfunc()

p = multiprocessing.Process(target=abc)
p.start()
while(1):
    time.sleep(1)
    if(p.is_alive()==False):
        print "restarting process"
        p = multiprocessing.Process(target=abc)
        p.start()
    else:
        print "process still running"
Advertisements

Written by azimout

07/03/2011 at 10:17

Posted in Howto

2 Responses

Subscribe to comments with RSS.

  1. http://supervisord.org/ (i haven’t tested it yet, but i will set it up today or tomorrow in combination with nginx/gunicorn)

    Danilo

    07/03/2011 at 17:43

    • Very interesting, I was not aware of it (nor did it come up in any of my searches). Unfortunately it won’t do, because I need something that works also under Windows.

      azimout

      07/03/2011 at 18:10


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: