Multiple pages on the Internet, including answers to this SO question and this page from a training company, say that you should handle Ctrl-C in python with code similar to:
import signal
import sys
import time
try:
while True:
print('Running...')
time.sleep(10)
except KeyboardInterrupt:
print('Ctrl-C pressed!')
sys.exit(0)
However, there is a fairly significant problem if you use code with this sort of solution from a Bash loop, like this:
while true; do
./python_script.py
done
The issue is that because Python is absorbing the Ctrl-C, Bash doesn't know the script exitted abnormally, so just carries on around the loop and it becomes very difficult to exit.
I asked AI, and it suggested first to give a specific error code to the sys.exit call, which didn't work, then to use the raise call, which did stop the script in a way that caused Bash to exit the loop, but also still gives the Python stack trace.
When asked for a better solution, all the AI could come up with was to add import os, and then use the very un-Pythonic looking:
signal.signal(signal.SIGINT, signal.SIG_DFL)
os.kill(os.getpid(), signal.SIGINT)
Is there really no elegant way to do this properly from Python?