Skip to content

Q&A · Answered

How to handle keyboard interrupts in Python

asked 9 months, 1 week ago 1980 views 1 answer
39

My script should clean up when user presses Ctrl+C. How do I handle this?

1 Answer

One accepted
27

Accepted answer

Not confirmed since it was written, 9 months, 1 week ago
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")

Your answer

Say what you tried, not only what worked — the next person needs the reasoning. Code goes in a fenced block.

Shown beside your answer and never checked, so it cannot be a name someone already has here.

No account needed to answer. Sign in instead and it carries your name and earns reputation.