Terminating a Python Script

If you run a Python script, you may want to kill it during the program run, before the program ends. You can do it manually or from inside the code.

Terminate the program manually

Take a look at the following script:

This program will run indefinitely unless you stop it on purpose.

If you run it from the command line, you will be able to terminate it with the following keyboard shortcut:

Ctrl + C

After you use it, the Python interpreter will display a response, informing you that the program was interrupted with the keyboard shortcut.

If there is the following line of code inside your program: except KeyboardInterrupt or just a normal except, this keyboard shortcut will not work.

Here’s an example:

Each time you press Ctrl + C, the KeyboardInterrupt exception is handled, and the code is continued.

In such a case, if you work on Windows, you can use a different shortcut:

Ctrl + Pause / Break

If you are working on Unix / Linux system, you can use:

Ctrl + Z

It will not kill, but suspend the process. After you get access to the console, you can use jobs to display suspended tasks and kill it with the kill command. To kill the first suspended job, you can write kill %1.

Terminate the program from inside the code

So far, we used different methods to stop program execution manually. This time we are going to do it by adding a code to terminate the program.

Let’s take the last example and modify it.

Last time, when we tried to use Ctrl + C, the exception was handled, and the pass statement continued the loop. This time, instead of the pass, there is the quit function.

Now, if you press Ctrl + C, the exception is handled, and the quit function will terminate the code.

There is another example of how you can use quit.

This code will display the message and then end the program.

Besides quit, there are more ways to terminate the program.

MethodDefinition
quitTerminates the program.
exitWorks in the same way as quit. They both exist to make Python more user-friendly.
sys.exitIt’s the same as the two previous functions. The use of sys.exit is considered to be a good practice because it uses the sys module, which is always there.
raise SystemExitThis exception is raised by the sys.exit() function.