How To Stop Python Script In Linux

In this tutorial, we will discuss different methods on how to stop a Python script running in a Linux environment.

Although Python is a powerful and versatile programming language, there are instances when you need to manually stop or terminate a running script.

Some of the reasons for stopping a Python script might be to debug the code, fix a computation, or load new data. Let’s explore different approaches to achieve this.

1. Stopping Python Script Using Keyboard Interrupt

The simplest method to stop a Python script in Linux is by using a keyboard interrupt. This can be done by pressing the Ctrl + C keys simultaneously.

For example, consider a Python script named example.py running in the terminal:

To stop this script, simply press Ctrl + C. The script will be interrupted and terminated immediately.

2. Using the “kill” Command to Stop Python Script

Another approach to stopping a Python script is by using the kill command. This method requires the process ID (PID) of the running script. You can find the PID using the ps command in conjunction with the grep command:

Once you have identified the PID, you can use the kill command on that PID:

Replace PID with the actual process ID found in the previous step.

Note that if the script is running as a background process, you might need to use kill -9 PID to enforce the termination.

3. Using the “pkill” Command to Stop Python Script

The pkill command is another option to stop a Python script. It terminates all instances of a script by matching the script name, without requiring the process ID:

This will terminate any running instances of the example.py script.

4. Terminating Script Programmatically

If you want to stop the script programmatically, you can utilize the os and sys modules available in Python:

Replace exit_code with your desired exit code (usually 0 for successful termination, and 1 for an error).

Conclusion

In this article, we have discussed four different approaches to stopping a Python script in Linux, including keyboard interrupts, the use of kill and pkill commands, and programmatically using os._exit() and sys.exit() methods.

Each method has its own implications and use cases, so choose the one that best fits your needs.