~/Blog

Brandon Rozek

Photo of Brandon Rozek

PhD Student @ RPI, Writer of Tidbits, and Linux Enthusiast

Quick Python: Interrupts

Published on

Updated on

Warning: This post has not been modified for over 2 years. For technical posts, make sure that it is still relevant.

This post is part of a new series I’m starting where I quickly outline small Python snippets.

If you have an application that you want to gracefully exit when the user presses CTRL-C here’s the short snippet

import signal
import sys

# Function that gets called when interrupt is found
def signal_handler(sig, frame):
  print('You pressed Ctrl+C!')
  sys.exit(0)

# Attach the function to the interrupt signal
signal.signal(signal.SIGINT,signal_handler)

print('Press Ctrl+C')

Have any questions or want to chat: Reply via Email

Enjoyed this post?

Published a response to this? :