How to Force exiting from program/script

A

Alex

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

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

# Loop
while True:
....many lines....
 
D

Diez B. Roggisch

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

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

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

This works for me:

import threading
import time

def work():
while True:
pass



t = threading.Thread(target=work)
t.setDaemon(True)
t.start()

time.sleep(10)
raise SystemExit


The trick is to raise the SystemExit in the main-thread.

Diez
 
P

Piet van Oostrum

Alex said:
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
loop:

import signal, os
from threading import Timer

signalcode = signal.SIGALRM
class AlarmError(Exception):
pass

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()
try:
function()
except AlarmError, e:
print e
print 'Execution aborted'

def long_function():
while True:
pass

print "The everlasting command"
execute(long_function, 10)
print "The End"
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,997
Messages
2,570,240
Members
46,830
Latest member
HeleneMull

Latest Threads

Top