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?

  • CTRL+C historically has stopped only the current job-in-process, and not brought down the entire stack that job depends upon. Or it Copies whatever you've highlighted in a display. There is a long list of stuff that CTRL+C historically has never terminated: Display servers, daemons, interpreters, network connections, etc.
    – user535733
    Mar 31, 2020 at 20:12

2 Answers 2


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 or python3 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. by python3 my_script.py), then unless the KeyboardInterrupt is handled by the script, the whole program will stop when the exception is raised.

  • Can I do the same with a C program? If a function is running inside the main is it possible to just stop that function and return the control to main()?
    – Ano.Smith
    Apr 1, 2020 at 1:48
  • I believe this would require you to use a signal handler. Programming questions like that are probably better on Stack Overflow rather than askubuntu - this thread might be able to help you.
    – Andy J
    Apr 1, 2020 at 20:38

It's worth pointing out from the docs that you need to handle KeyboardInterrupt explicitly, even if you already have a catch for Exception:

The exception inherits from BaseException so as to not be accidentally caught by code that catches Exception and thus prevent the interpreter from exiting.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.