Skip to content

Instantly share code, notes, and snippets.

@westphahl
Created July 22, 2015 17:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save westphahl/a41b9f46191b34bfbd4e to your computer and use it in GitHub Desktop.
Save westphahl/a41b9f46191b34bfbd4e to your computer and use it in GitHub Desktop.
context manager to block signals
import time
import signal
class SignalBlocker:
def __init__(self, signal):
self._signal = signal
self._signal_blocked = False
def _handler(self, signum, frame):
self._signal_blocked = True
def __enter__(self):
self._original_handler = signal.getsignal(self._signal)
signal.signal(self._signal, self._handler)
def __exit__(self, exc_type, exc_val, exc_tb):
signal.signal(self._signal, self._original_handler)
if self._signal_blocked:
raise Exception("Ctrl-C received")
if __name__ == "__main__":
with SignalBlocker(signal.SIGINT):
for i in range(5):
time.sleep(1)
print("critical section")
print("outside section")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment