39
My script should clean up when user presses Ctrl+C. How do I handle this?
Loading...
Q&A · Answered
My script should clean up when user presses Ctrl+C. How do I handle this?
Accepted answer
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")Say what you tried, not only what worked — the next person needs the reasoning. Code goes in a fenced block.