I am trying to write a context manager to timeout a process, and I have following:
import threading
import _thread
import time
from contextlib import contextmanager
@contextmanager
def raise_timeout(timeout):
timer = threading.Timer(timeout, _thread.interrupt_main)
timer.start()
try:
yield
except:
print(f"timeout after {timeout} seconds")
raise
finally:
timer.cancel()
with raise_timeout(1):
time.sleep(5)
the problem is when the time out is reached, it still waits for the time.sleep(5) to finish before the exception is raised. when I run the script I waited for 5 seconds before getting the following output in the terminal:
> timeout after 1 seconds Traceback (most recent call last): File
> "scratch1.py",
> line xx, in <module>
> time.sleep(5) KeyboardInterrupt
but if I run the timer directly as below I got the exception right after the 1 second timeout.
timer = threading.Timer(1, _thread.interrupt_main)
timer.start()
I just wonder how the process in the with statement can block the exception till it finishes?