Latest Code Tutorials

How to Stop Python Script From Execution


Is it possible to stop the execution of a python script at any line with a command? The answer is Yes. You can stop the Python script at any point in a given time. You can do it manually or programmatically, and in this tutorial, we will see each approach one by one.

Python stop script

There are many ways to stop Python scripts from executing in the system.

  1. To stop a python script, just press Ctrl + C.
  2. Use exit() function to terminate Python script execution programmatically.
  3. Use the sys.exit() method to stop even multi-threaded programs.
  4. Using an interactive script with just exit.
  5. You can use pkill -f name-of-the-python-script.
  6. Using OS._exit(0) method.

Press CTRL + C to terminate the Python script

To stop a script in Python, press Ctrl + C. If you are using Mac, press Ctrl + C. If you want to pause the process and put it in the background, press Ctrl + Z (at least on Linux). Then, if you want to kill it, run kill %n where “n” is the number you got next to “Stopped” when you pressed Ctrl + Z. If you want to resume it, run fg.

If your code is running at an interactive console, pressing Ctrl + C will raise the KeyboardInterrupt exception on the main thread.

If your Python code doesn’t catch that exception, then the KeyboardInterrupt will cause Python to exit. However, an except KeyboardInterrupt: block, or something like a bare except, will prevent this mechanism from truly stopping the script from running.

Sometimes if KeyboardInterrupt is not working, you can send a SIGBREAK signal instead; on Windows, Ctrl + Pause/Break may be handled by the interpreter without generating a catchable KeyboardInterrupt exception.

How to stop script programmatically in Python

To stop Python script programmatically, use the exit() function in your code. 

There is an even more ideal solution to stop the script and to do that, and you can use the sys.exit() method.

The sys.exit() function terminates Python script even if you are running things parallel through the multiprocessing package.

To use the sys.exit() in your program, you must import it at the start of your file.

import sys

Let’s see the following example.

import sys


dct = {}
dct.__setitem__('a', 21)

If you run the program, then it will not give you any output because the program is stopped before it executes the dict code.

Using OS._exit(0) method

You can also terminate the Python script execution using the os._exit(0) method. To use the _exit(0) method, you need to import the os module at the start of the file.

import os


dct = {}
dct.__setitem__('a', 21)

It will not give you any output since the program is already terminated by the os._exit(0) function.

That is it for this tutorial.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.