Last active
July 17, 2024 04:05
-
-
Save nickeldan/3e985c843961c9c17f9be723cffcd97d to your computer and use it in GitHub Desktop.
Context manager for temporarily blocking KeyboardInterrupt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import signal | |
import threading | |
class SigintHandler: | |
def __init__(self): | |
self._orig_handler = None | |
self._interrupted = threading.Event() | |
@property | |
def interrupted(self): | |
return self._interrupted.wait(0) | |
def _handler(self, *args): | |
self._interrupted.set() | |
def __enter__(self): | |
self._orig_handler = signal.signal(signal.SIGINT, self._handler) | |
return self | |
def __exit__(self, *args): | |
signal.signal(signal.SIGINT, self._orig_handler) | |
self._orig_handler = None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment