I am trying to understand the reason why the whole Python process does not get killed when I press Ctrl + C inside and infinite loop or for that matter any Python function that I am running in terminal and only the loop/function is stopped?
I am trying to understand the reason why the whole Python process does not get killed when I press Ctrl + C inside and infinite loop or for that matter any Python function that I am running in terminal and only the loop/function is stopped?
It's because of the design of the Python interpreter and interactive session.
Ctrl + C sends a signal, SIGINT, to the Python process, which the Python interpreter handles by raising the KeyboardInterrupt exception in the currently-running scope.
If the interpreter is running in an interactive session (i.e. by running
python
orpython3
at the console), then the exception in the current function is printed and you return to the Python prompt. If the interpreter is running a script (e.g. bypython3 my_script.py
), then unless the KeyboardInterrupt is handled by the script, the whole program will stop when the exception is raised.It's worth pointing out from the docs that you need to handle
KeyboardInterrupt
explicitly, even if you already have a catch forException
:The exception inherits from BaseException so as to not be accidentally caught by code that catches Exception and thus prevent the interpreter from exiting.