Is there a way to stop time.sleep in windows?

In the nix python signal, I can stop the sleep before it is ready. Is there any similar mechanism available on Windows - it seems that all methods ultimately intercept code only after sleep?

Code example:

from time import sleep .. do something that will intercept the sleep try: sleep(60) finally: print 'how to get here under 60 seconds in windows?' 

A similar question that has no answer for windows: time.sleep () interrupt / interrupt in python

+6
python windows
source share
2 answers

The Python documentation for signal reads:

• Although Python signal handlers are called asynchronously as long as the Python user, they can only occur between the "atomic" instructions of the Python interpreter. This means that signals arriving during lengthy calculations performed exclusively in C (for example, regular expression matches on large text bodies) can be delayed for an arbitrary amount of time.

while time says:

The actual pause time may be less than the requested one, since any caught signal will stop sleep () after this signal is executed.

On Windows, apparently, time.sleep() not executed according to the documentation, since the signal handler received during sleep does not work until the full duration of sleep has ended. The following example:

 import signal, time def handler(signum, frame): print('Signal handler called with signal', signum) signal.signal(signal.SIGINT, handler) print("signal set, sleeping") time.sleep(10) print("sleep done") 

prints:

 signal set, sleeping Signal handler called with signal 2 sleep done 

when the first line occurs immediately, and the second after 10 seconds, regardless of when the interrupt occurs.

According to Thomas K, the best strategy would be to use threads and synchronization.

+4
source share

I'm not sure if this will do it for you, but here is a bit of a workaround:

 for i in range(60): if checkIfIShouldInterruptSleep(): break time.sleep(1) print "Finished Sleeping!" 

It is only accurate for the second, but can serve your purpose. Happy coding!

+1
source share

All Articles