Skip to content

Instantly share code, notes, and snippets.



Last active Dec 27, 2018
What would you like to do?
How to catch and handle signals in python3
# How to handle signals in python
# Use ctrl+c to send SIGINT and ctrl+z to send SIGTSTP (then `fg` to send SIGCONT)
import signal, time, sys, os
import logging
from logging import info
def sigint_handler(signum, frame):
info(f'sigint_handler: Received signal {signum} on frame {frame}')
def sigtstp_handler(signum, frame):
info(f'sigtstp_hangler: Received signal {signum} on frame {frame}')
# ... release your resources here ...
# Remove our handler
signal.signal(signum, signal.SIG_DFL)
# Resend signal to pause process
os.kill(os.getpid(), signum)
# Back from suspend -- reestablish the handler.
signal.signal(signal.SIGTSTP, sigtstp_handler)
def sigcont_handler(signum, frame):
info(f'sigcont_handler: Received signal {signum} on frame {frame}')
time.sleep(0.5) # acquire resources here ...
info('Ready to go')
logging.basicConfig(level=logging.INFO, format='\n%(message)s')
# Assign handlers to signals
signal.signal(signal.SIGINT, sigint_handler)
signal.signal(signal.SIGTSTP, sigtstp_handler)
signal.signal(signal.SIGCONT, sigcont_handler)
while True:
for col in range(80):
print('a', end='', flush=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.