How to Stop Python Script From Execution

0
2778
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; in this tutorial, we will see each approach individually.

Python stop script

  1. To stop a python script, just press Ctrl + C.
  2. Use the 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 runs 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, the interpreter may handle Ctrl + Pause/Break without generating a catchable KeyboardInterrupt exception.

How to stop script programmatically in Python

To stop Python script programmatically, use your code’s exit() function. There is an even more ideal solution to stop the script, and you can use the sys.exit() method.

The sys.exit() function terminates Python script even if you run 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

sys.exit()

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

If you run the program, 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 must import the os module at the start of the file.

import os

os._exit(0)

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

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.

Related posts

Python clear console

Python clear screen

Leave A Reply

Please enter your comment!
Please enter your name here

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