Why does Ctrl + C not kill Python running in terminal?

22,039

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.

Share:
22,039

Related videos on Youtube

Ano.Smith
Author by

Ano.Smith

Updated on September 18, 2022

Comments

  • Ano.Smith
    Ano.Smith over 1 year

    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?

    • Admin
      Admin about 4 years
      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.
  • Ano.Smith
    Ano.Smith about 4 years
    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()?
  • Andy J
    Andy J about 4 years
    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.