I have a function that occasionally hangs.
Normally I would set an alarm, but I'm in Windows and it's unavailable.
Is there a simple way around this, or should I just create a thread that calls time.sleep()
?
Try calling signal. alarm(0) when you want to disable the alarm. In all likelyhood it just calls alarm() in libc, and the man alarm says that alarm(0) "... voids the current alarm and the signal SIGALRM will not be delivered."
If time is non-zero, this function requests that a SIGALRM signal be sent to the process in time seconds. Any previously scheduled alarm is canceled (only one alarm can be scheduled at any time). The returned value is then the number of seconds before any previously set alarm was to have been delivered.
You can use the functions in Python's built-in signal module to set up signal handlers in python. Specifically the signal. signal(signalnum, handler) function is used to register the handler function for signal signalnum .
The following are 30 code examples for showing how to use signal.alarm () . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
The SIGILLand SIGTERMsignals are not generated under Windows. They are included for ANSI compatibility. Therefore, you can set signal handlers for these signals by using signal, and you can also explicitly generate these signals by calling raise.
For example, you can call signaltwice to assign the same handler to two different signals, and then test the sigargument in the handler to take different actions based on the signal received.
Return the system description of the signal signalnum, such as “Interrupt”, “Segmentation fault”, etc. Returns None if the signal is not recognized. New in version 3.8. Return the set of valid signal numbers on this platform.
The most robust solution is to use a subprocess, then kill that subprocess. Python2.6 adds .kill() to subprocess.Popen().
I don't think your threading approach works as you expect. Deleting your reference to the Thread object won't kill the thread. Instead, you'd need to set an attribute that the thread checks once it wakes up.
Here's how the original poster solved his own problem:
Ended up going with a thread. Only trick was using os._exit
instead of sys.exit
import os
import time
import threading
class Alarm (threading.Thread):
def __init__ (self, timeout):
threading.Thread.__init__ (self)
self.timeout = timeout
self.setDaemon (True)
def run (self):
time.sleep (self.timeout)
os._exit (1)
alarm = Alarm (4)
alarm.start ()
time.sleep (2)
del alarm
print 'yup'
alarm = Alarm (4)
alarm.start ()
time.sleep (8)
del alarm
print 'nope' # we don't make it this far
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With