Skip to content

Instantly share code, notes, and snippets.

@nickeldan
Last active July 17, 2024 04:05
Show Gist options
  • Save nickeldan/3e985c843961c9c17f9be723cffcd97d to your computer and use it in GitHub Desktop.
Save nickeldan/3e985c843961c9c17f9be723cffcd97d to your computer and use it in GitHub Desktop.
Context manager for temporarily blocking KeyboardInterrupt
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