When you press Ctrl+C in the terminal, Python raises a KeyboardInterrupt
, which you can catch.
But when you press the Stop button in PyCharm, PyCharm doesn’t send KeyboardInterrupt
. Instead, it terminates the process by sending a signal — usually SIGTERM
(terminate) or sometimes SIGKILL
(kill).
If it’s SIGKILL
, you can’t catch it — the process is killed immediately.
If it’s SIGTERM
, you can handle it with the signal
module and do your cleanup before exiting.
Here’s a small example:
import signal
import sys
import time
a = 0
def cleanup(signum, frame):
global a
print("Cleaning up before exit...")
a = 0
sys.exit(0)
# Handle Ctrl+C and PyCharm's Stop button
signal.signal(signal.SIGINT, cleanup)
signal.signal(signal.SIGTERM, cleanup)
a = 1
print("Loop started...")
while True:
time.sleep(1)