I have a script that was copying data from SD card. Due to the huge amount of files/filesize, this might take a longer period of time than expected. I would like to exit this script after 5 minutes. How can I do so?
Asked
Active
Viewed 2,950 times
1
-
You could try setting an alarm signal to go off in 5 minutes and have the alarm signal handler exit the process. – seaotternerd May 12 '15 at 08:49
-
Could you possible to post a sample answer so I can check and select as an answer. – Eric T May 12 '15 at 08:51
-
1Windows or Unix? If Unix: http://stackoverflow.com/a/22348885/47351 – RvdK May 12 '15 at 08:51
-
Unix, sorry to be new in python is this `with timeout(seconds=300):` will solve my problem? – Eric T May 12 '15 at 08:55
2 Answers
4
It's hard to verify that this will work without any example code, but you could try something like this, using the signal module:
At the beginning of your code, define a handler for the alarm signal.
import signal
def handler(signum, frame):
print 'Times up! Exiting..."
exit(0)
Before you start the long process, add a line like this to your code:
#Install signal handler
signal.signal(signal.SIGALRM, handler)
#Set alarm for 5 minutes
signal.alarm(300)
In 5 minutes, your program will receive the alarm signal, which will call the handler, which will exit. You can also do other things in the handler if you want.

seaotternerd
- 6,298
- 2
- 47
- 58
1
Here, the threading module comes in handily:
import threading
def eternity(): # your method goes here
while True:
pass
t=threading.Thread(target=eternity) # create a thread running your function
t.start() # let it run using start (not run!)
t.join(3) # join it, with your timeout in seconds

FinalState
- 91
- 1
- 4