How to handle keyboard interrupts in Python
Answered
39
My script should clean up when user presses Ctrl+C. How do I handle this?
C
Asked by
cloud_arch
Platinum
•
776 rep
1 Answer
27
import signal
import sys
def cleanup():
print("\nCleaning up...")
# Close connections, save data, etc.
def signal_handler(signum, frame):
cleanup()
sys.exit(0)
# Register handler
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
# Or use try-except
try:
while True:
# Main loop
pass
except KeyboardInterrupt:
cleanup()
print("Exited gracefully")
P
Platinum
•
447 rep
Your Answer
You need to be logged in to answer questions.
Log In to Answer