Last active
December 27, 2018 21:12
-
-
Save julien-h2/18934aaf5eb0ec17b6617cbe1b72f844 to your computer and use it in GitHub Desktop.
How to catch and handle signals in python3
This file contains hidden or 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
# | |
# https://scripting.tips/complete-guide-to-writing-command-line-tools.html | |
# | |
# 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}') | |
sys.exit(0) | |
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) | |
time.sleep(0.1) | |
print() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment