How to handle keyboard interrupts in Python

Answered
Jan 05, 2026 1504 views 1 answers
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
Answered by python_dev 1 week, 2 days ago
Platinum 447 rep

Your Answer

You need to be logged in to answer questions.

Log In to Answer

Related Questions

Hot Questions

No hot questions available.