How Do You End Scripts in Python?
Programming means giving instructions to a computer on how to perform a task. These instructions are written using a programming language. An organized sequence of such instructions is called a script.
As a programmer, your main job is to write scripts (i.e. programs). However, you also need to know how scripts can end. In this article, we will go over different ways a Python script can end. There is no prerequisite knowledge for this article, but it is better if you are familiar with basic Python terms.
If you are new to programming or plan to start learning it, Python is the best way to start your programming adventure. It is an easy and intuitive language, and the code is as understandable as plain English.
Scripts are written to perform a task; they are supposed to end after the task is completed. If a script never ends, we have a serious problem. For instance, if there is an infinite while loop in the script, the code theoretically never ends and might require an external interruption.
It is important to note that an infinite while loop might be created on purpose. A script can be written to create a service that is supposed to run forever. In this case, the infinite loop is intentional and there is no problem with that.
The end of a Python script can be frustrating or satisfying, depending on the result. If the script does what it is supposed to do, then it’s awesome. On the other hand, if it ends by raising an exception or throwing an error, then we will not be very happy.
5 Ways to End Python Scripts
Let’s start with the most common and obvious case: a script ends when there are no more lines to execute.
1. All the Lines Are Executed
The following is a simple script that prints the names in the list, along with the number of characters they contain:
mylist = ["Jane", "John", "Ashley", "Matt"] for name in mylist: print(name, len(name))
Jane 4 John 4 Ashley 6 Matt 4
The script does its job and ends. We all are happy.
Python scripts, or scripts in any other programming language, can perform a wide range of operations. In many cases, we cannot visually check the results. For instance, the job of a script might be reading data from a database, doing a set of transformations, and writing the transformed data to another database.
In scripts that perform a series of operations, it’s a good practice to keep a log file or add print statements after each individual task. It lets us do simple debugging in case of a problem. We can also check the log file or read the output of print statements to make sure the operation was completed successfully.
2. Uncaught Exception
It usually takes several iterations to write a script that runs without an error; it’s rare to get it right the first time. Thus, a common way that a script ends is an uncaught exception; this means there is an error in the script.
When writing scripts, we can think of some possible issues and place try-except blocks in the script to handle them. These are the exceptions that we are able to catch. The other ones can be considered uncaught exceptions.
Consider the following code:
mylist = ["Jane", "John", 2, "Max"] for i in mylist: print(f"The length of is ")
The length of Jane is 4 The length of John is 4 Traceback (most recent call last): File "", line 4, in TypeError: object of type 'int' has no len()
The code prints the length of each item in the list. It executes without a problem until the third item, which is an integer. Since we cannot apply the len function to an integer, the script throws an error and ends.
We can make the script continue by adding a try-except block.
mylist = ["Jane", "John", 2, "Max"] for i in mylist: try: print(f"The length of is ") except TypeError: print(f" does not have a length!")
The length of Jane is 4 The length of John is 4 2 does not have a length! The length of Max is 3
What does this try-except block do?
- It prints the f-string that includes the values and their lengths.
- If the execution in the try block returns a TypeError, it is caught in the except block.
- The script continues the execution.
The script still ends, but without an error. This case is an example of what we explained in the first section.
3. sys.exit()
The sys module is part of the Python standard library. It provides system-specific parameters and functions.
One of the functions in the sys module is exit , which simply exits Python. Although the exit behavior is the same, the output might be slightly different depending on the environment. For instance, the following block of code is executed in the PyCharm IDE:
import sys number = 29 if number < 30: sys.exit() else: print(number)
Process finished with exit code 0
Now, let’s run the same code in Jupyter Notebook:
import sys number = 29 if number < 30: sys.exit() else: print(number)
An exception has occurred, use %tb to see the full traceback. SystemExit
The sys.exit function accepts an optional argument that can be used to output an error message. The default value is 0, which indicates successful termination; any nonzero value is an abnormal termination.
We can also pass a non-integer object as the optional argument:
import sys number = 29 if number < 30: sys.exit("The number is less than 30.") else: print(number)
An exception has occurred, use %tb to see the full traceback. SystemExit: The number is less than 30.
The sys.exit() function raises the SystemExit exception, so the cleanup functions used in the final clause of a try-except-finally block will work. In other words, we can catch the exception and handle the necessary cleanup operations or tasks.
4. exit() and quit()
The exit() and quit() functions are built into Python for terminating a script. They can be used interchangeably.
The following script prints the integers in the range from 0 to 10. If the value becomes 3, it exits Python:
for i in range(10): print(i) if i == 4: exit()
0 1 2 3 Process finished with exit code 0
Note: The exit() function also raises an exception, but it is not intercepted (unlike sys.exit() ). Therefore, it is better to use the sys.exit() function in production code to terminate Python scripts.
5. External Interruption
Another way to terminate a Python script is to interrupt it manually using the keyboard. Ctrl + C on Windows can be used to terminate Python scripts and Ctrl + Z on Unix will suspend (freeze) the execution of Python scripts.
If you press CTRL + C while a script is running in the console, the script ends and raises an exception.
Traceback (most recent call last): File "", line 2, in KeyboardInterrupt
We can implement a try-except block in the script to do a system exit in case of a KeyboardInterrupt exception. Consider the following script that prints the integers in the given range.
for i in range(1000000): print(i)
We may want to exit Python if the script is terminated by using Ctrl + C while its running. The following block of code catches the KeyboardInterrupt exception and performs a system exit.
for i in range(1000000): try: print(i) except KeyboardInterrupt: print("Program terminated manually!") raise SystemExit
Program terminated manually! Process finished with exit code 0
We have covered 5 different ways a Python script can end. They all are quite simple and easy to implement.
Python is one of the most preferred programming languages. Start your Python journey with our beginner-friendly Learn Programming with Python track. It consists of 5 interactive Python courses that gradually increase in complexity. Plus, it’s all interactive; our online console lets you instantly test everything you learn. It is a great way to practice and it makes learning more fun.
What's more, you don't need to install or set anything up on your computer. You only need to be willing to learn; we'll take care of the rest. Wait no more – start learning Python today!
Kill Process By PID in Python
You can kill a process via its process identifier, pid, via the os.kill() function.
In this tutorial you will discover how to kill a process via its pid.
Need To Kill a Process by PID
A process is a running instance of a computer program.
Every Python program is executed in a Process, which is a new instance of the Python interpreter. This process has the name MainProcess and has one thread used to execute the program instructions called the MainThread. Both processes and threads are created and managed by the underlying operating system.
Sometimes we may need to create new child processes in our program in order to execute code concurrently.
Python provides the ability to create and manage new processes via the multiprocessing.Process class.
You can learn more about multiprocessing in the tutorial:
In multiprocessing, we may need to kill a process by its process identifier or PID.
This may be for many reasons, such as:
- The task executed by the process is no longer required.
- The process has had an error or is out of control.
- The main program is closing down due to a user request.
How can we kill a process via its pid in Python?
Run your loops using all CPUs, download my FREE book to learn how.
How To Kill a Process via its PID
You can kill a process via its pid with the os.kill() function.
The os.kill function takes two arguments, the process identifier (pid) to kill, and the signal to send to kill the process.
The signal is a constant from the signal module, such as signal.SIGINT or signal.SIGKILL.
We need to know the pid for the process that is to be killed.
This can be retrieved from the multiprocessing.Process instance for the process via the pid attribute.
The multiprocessing.Process instance may be managed by the parent process when the child process is created, or accessed via a module function such as multiprocessing.active_children() or multiprocessing.parent_process().
You can learn more about getting the process pid in the tutorial:
The SIGINT or signal interrupt can be used to terminate the target process, which is equivalent to the user pressing CONTROL-C on the process. Alternately, the SIGKILL or signal kill process can be used to terminate the process forcefully.
The difference between SIGINT and SIGKILL is that it is possible for a process to detect and handle a SIGINT, whereas a SIGKILL cannot be handled.
Now that we know how to kill a process via pid, let’s look at some worked examples.
Confused by the multiprocessing module API?
Download my FREE PDF cheat sheet
Kill Current Process via PID
It is possible to kill the current process via pid.
This can be achieved by first getting the pid for the current process, then calling os.kill() with the pid and the signal to kill the process, such as SIGKILL.
First, we can get the pid for the current process using the os.getpid(), and report the result.