How to Force exiting from program/script

Piet van Oostrum piet at
Thu Jul 16 04:48:57 EDT 2009

>>>>> Alex <magobin at> (A) a écrit:

>A> hi at all,
>A>  I have made a script with a while loop and I want that after 30
>A> seconds the program stop and exit . But the code like this doesn't
>A> run:
>A> In the Console I can see work so that function is correctly called...

>A> #Function to exit
>A> def exit():
>A>     print "work"
>A>     raise SystemExit()
>A> t = threading.Timer(30.0, exit)
>A> t.start()

>A> # Loop
>A> while True:
>A> ...many lines....

This code gives you a bit more control as it doesn't just force a system
exit, but allows you to continue some other work after aborting the

import signal, os
from threading import Timer

signalcode = signal.SIGALRM
class AlarmError(Exception):

def handler(signum, frame):
    raise AlarmError, "command lasts too long"

signal.signal(signalcode, handler)

def interrupt():
    os.kill(os.getpid(), signalcode)

def execute(function, timeout):
    Timer(timeout, interrupt).start()
    except AlarmError, e:
        print e
        print 'Execution aborted'

def long_function():
    while True:
print "The everlasting command"
execute(long_function, 10)
print "The End"

Piet van Oostrum <piet at>
URL: [PGP 8DAE142BE17999C4]
Private email: piet at

More information about the Python-list mailing list