How to Exit a Python script?
Exiting a Python script refers to the process of termination of an active python process. In this article, we will take a look at exiting a python program, performing a task before exiting the program, and exiting the program while displaying a custom (error) message.
Exiting a Python application
There exist several ways of exiting a python application. The following article has explained some of them in great detail.
Example: Exit Using Python exit() Method
Python3
Output:
Detecting Script exit
Sometimes it is required to perform certain tasks before the python script is terminated. For that, it is required to detect when the script is about to exit. atexit is a module that is used for performing this very task. The module is used for defining functions to register and unregister cleanup functions. Cleanup functions are called after the code has been executed. The default cleanup functions are used for cleaning residue created by the code execution, but we would be using it to execute our custom code.
How to End Program in Python
Giving a computer instructions on how to carry out a task is referred to as programming. A programming language was used to create these instructions. A script is a set of such instructions that have been organized.
The primary function of a programmer is to create scripts (i.e. programs). You must be aware of how scripts can end or terminate, though. We shall discuss many ways of "How to End Program in Python" in this article. This article doesn't require any prior knowledge, but it would help if you were familiar with Python basics.
How to End Program in Python?
You must be already aware that as a programmer we are supposed to create programming scripts. Scripts are created to carry out specific tasks, and they are meant to finish when those tasks are finished. We have a major issue if a script never ends. For instance, if the script contains an infinite while loop, the code theoretically never finishes and may need to be interrupted externally.
Sometimes, we intentionally write a script that is supposed to run infinitely. There is no issue with the infinite loop in this situation because it is intentional. Hence, if the script executes successfully and achieves its intended goals, it is great. But on the other hand, it would create a blunder if the script ends by throwing an error or raising an exception.
When we write a Python script, sometimes we realize that there is a need to stop the execution of the script at a certain point during execution. This can be achieved by Python exit commands.
Different Ways to End a Program in Python
We have got several ways through which we can end a program in Python. They are as stated below:
- Using KeyboardInterrupt
- Using sys.exit()
- Using exit() function
- Using quit() command
- Through os._exit() function
- By handling Uncaught Exceptions
- Through raise SystemExit
Now, let us cover all of these ways to end a program in Python in detail.
Ending Program in Python Using KeyboardInterrupt
One of the approaches to ending the program in Python is to manually stop it with keyboard interruption. Python scripts can be stopped using Ctrl + C on Windows, and Ctrl + Z on Unix will pause (freeze) the Python script's execution.
While a script is executing on the terminal, pressing CTRL + C causes the script to terminate and raise an exception. Let us look into the example below to understand it in further detail.
FYI: KeyboardInterrupt is a Python exception that is thrown when a user or programmer interrupts a program's usual execution. While executing the program, the Python interpreter checks for any interrupts on a regular basis.
Code:
Output:
Explanation: In the above example, we have written a code that will run infinitely. In simple words, we have written the code for an infinite while loop.
Now, midway through the code, we manually interrupt and stop its execution by pressing the CTRL + C on our keyboard. Hence, we are then prompted with the KeyboardInterrupt exception and our program ends abruptly. So we prevented this code from running infinitely by interrupting it through a keyboard and hence ended the program.
However, this is not the most efficient way since you can see, we got the KeyboardInterrupt exception while doing so, and the code exited abnormally.
If a KeyboardInterrupt exception occurs, we may use a try-except block in the script to perform a system exit.
Code:
Output:
Explanation: In the above code, we have again ended our Python program manually through keyboard interruption. But here we have smoothly handled the exception. The try-except block of code catches the KeyboardInterrupt exception and performs a system exit without throwing any error.
Ending Program in Python Using sys.exit()
One of the approaches to ending the program in Python is using the sys.exit() . The Python standard library contains the sys module. It offers functions and parameters that are system-specific.
exit is a sys module function that simply terminates the Python code. The output that we get from the sys.exit() might be different depending upon the environment we have written the code. Let us look into the syntax of sys.exit() .
Syntax: Please note that we need to import the sys module before using the sys.exit() .
Parameters: The sys.exit() function takes an optional argument that can be any string, integer, or any other object.
Now, let us first code and see how do we end the program in Python using the sys.exit() .
Code:
Output:
Explanation: In the above code, we first imported the sys module to use the sys.exit() function. Then, we tried to check whether or not our variable satisfies the given condition. And, since in our code, the variable actually satisfies the condition, we end our Python program by using the sys.exit() function.
This is a very simple, yet convenient way to handle the exiting of the Python code when we are aware beforehand of when to stop our code.
Ready to take your Python skills to new heights? Enroll in Scaler Topics Python certification course and become a certified Python pro!
Ending Program in Python Using exit() Command:
The exit() function is in-built in Python and is defined in the site.py module. It can be considered as an alias for the quit() command (we will learn ahead in the article). The exit() command works only after the site modules are loaded, and hence it should not be used in the production-level codes.
The SystemExit exception is raised by the exit() command. In this case, exit(0) denotes a clean exit without any problems, whereas exit(1) denotes that a problem was caused during the program's termination.
Syntax: The syntax for exit() is very straightforward. We do not need to install or import any extra modules or packages because it comes in-built in Python. And it does not takes any parameters.
Code:
Output:
Explanation: In the above code, we tried to end our Python code by using the in-build function exit() . Hence, our for-loop ran only once and then exited. Even the next print statements were also not executed because the program terminated earlier due to the exit() function.
Ending Program in Python by using quit() Command
The quit() function can be considered an alternative to the exit() function in Python. It is also an in-built Python function that is used to terminate the Python codes.
When the system comes across the quit() function, it exits the Python program by closing the Python file itself. The quit() command also requires the site.py module to be imported. The SystemExit exception is raised by the quit() command in the background.
Syntax: The syntax for quit() is very straightforward. We do not need to install or import any extra modules or packages because it comes in-built in Python. And it does not takes any parameters.
Code:
Output:
Explanation: In the above code, we tried to end our Python code by using the in-build function quit() . Hence, our while loop ran only once and then exited. Even the next print statements were also not executed because the program terminated earlier due to the exit function.
Which to use — sys.exit() or exit() or quit() at Production Level?
The exit() or quit() function also raises the SystemExit exception, but it is not handled like in the case of sys.exit() . As a result, it is preferable to end Python scripts in production code using the sys.exit() function.
Apart from that, the site.py module must be loaded before using the exit() or quit() commands. Hence, it is better to use the sys.exit() command at the production level.
Ending Program in Python Through os._exit() Function
In some circumstances, the os._exit() command can be used to terminate a Python program with a specific status, without invoking any of the cleaning handlers, flushing stdio buffers, etc. This function requires importing the os module before exiting the program with os.exit() .
The os.exit() is generally used in the child processes after the os.fork() system call. Please note that it is a non-standard way to exit a process.
Code:
Output:
Explanation: In the above code, we terminated our Python program by using the os._exit() command.
Ending Program in Python by Handling Uncaught Exceptions
One of the approaches to ending the program successfully in Python is through handling the uncaught exceptions.
It is uncommon to build a script that works flawlessly on the first try; it typically requires multiple revisions. For the same reason, most of the scripts terminate with some uncaught exception, which eventually breaks our code and indicates that our script contains some bugs.
Hence, while writing code, we can insert try-except blocks in the areas which are prone to throw errors. It will then handle the execution of our code smoothly and end the code successfully, even if it contains some bug. This can be better understood with some examples. Hence, let us consider a scenario where our code can throw some errors.
Code:
Output:
Explanation: In the above code, we have tried to demonstrate how can an uncaught exception exist in our code, which will break our code if not handled carefully. So, we have created a fruitsdictionary and filled it with some data. While fetching the data from the dictionary using the dictionary key, there comes a point where the key does not exist in the dictionary. At that point, our code throws the KeyError .
Let us now see, how can we handle this exception and ensure a smooth ending of our Python code.
Code:
Output:
Explanation: In the above code, you can see how smoothly we handled the issue that was caused due to the missing key. We simply wrapped our code into a try-except block which prevented our code from breaking and performed the action we have defined in the except block.
This was just an example of how can we handle uncaught exceptions, but there are ample ways which you can use in your code to prevent any issue.
Ending Program in Python Through Raise SystemExit
SystemExit is an exception in Python which is raised by the sys.exit() method. The SystemExit exception is inherited from the BaseException . When the SystemExit exception is raised and is left unhandled, then the Python interpreter exits.
Interestingly, the SystemExit exception is raised in most of the methods of exiting Python programs (such as sys.exit() , exit() , and quit() ) we discussed above, but we can also raise this exception directly. Let us look into the code for the same.
Code:
Output:
Explanation: In the above code, we have manually tried to demonstrate how the SystemExit exception is raised. Once this exception is raised, our except block handles this exception by performing the instructions we have given to our code.
In Python, the SystemExit Exception is raised when the sys.exit() function is called.
Code:
Output:
Explanation: In the above code, we have demonstrated the working of sys.exit . We see that once the limit is 100, it raises the SystemExit exception and the program is terminated, printing the message we have passed to the print statement — 'Limit reached 100!!'. Use this Python Compiler to compile your code.
Related Programs in Python
Now that you have got a clear and crisp idea about "How to End Program in Python", I encourage you to go ahead and pick any of the below scaler articles to further enhance your knowledge in Python –
Conclusion
In this article, we learned about " How to End Program in Python ". Let us now go through the topics we covered and summarise them.
Как использовать функцию exit в скриптах Python
Функция exit в Python позволяет в любой момент остановить выполнение скрипта или программы. Это может понадобиться для обработки ошибок, тестирования и отладки, остановки программы при соблюдении каких-то условий.
Синтаксис exit() следующий:
Необязательный аргумент status представляет собой статус выхода. Это целочисленное значение, которое указывает на причину завершения программы. Принято считать, что статус 0 означает успешное выполнение, а любой ненулевой статус указывает на ошибку или ненормальное завершение.
Если аргумент status не указан, используется значение по умолчанию 0.
Вот пример использования функции exit в Python:
В этом примере программа выводит строку «Before exit». Но когда exit() вызывается с аргументом 1, программа немедленно завершается, не выполняя оставшийся код. Поэтому строка «After exit» не выводится.
От редакции Pythonist: также предлагаем почитать статьи «Как запустить скрипт Python» и «Создание Python-скрипта, выполняемого в Unix».
Как использовать функцию exit() в Python
Давайте напишем скрипт на Python и используем в нем функцию exit.
Пояснение кода
- Скрипт начинается с импорта модуля sys, который предоставляет доступ к функции exit() .
- Функция main() служит точкой входа в программу. Внутри этой функции можно добавлять свой код.
- Внутри функции main() можно выполнять различные операции. В данном примере мы просто выводим приветственное сообщение и спрашиваем пользователя, хочет ли он выйти.
- После получения пользовательского ввода мы проверяем, хочет ли пользователь выйти. Для этого сравниваем его ввод с «y» (без учета регистра). Если условие истинно, вызываем функцию exit_program() для завершения работы скрипта.
- Функция exit_program() выводит сообщение о том, что программа завершается, а затем вызывает sys.exit(0) для завершения программы. Аргумент 0, переданный в sys.exit() , означает успешное завершение программы. При необходимости вы можете выбрать другой код завершения.
- Наконец, при помощи переменной __name__ проверяем, выполняется ли скрипт как главный модуль. Если это так, вызываем функцию main() для запуска программы.
Best practices использования функции exit в Python
Импортируйте модуль sys
Чтобы использовать функцию exit(), необходимо импортировать модуль sys в начале скрипта. Включите в свой код следующую строку:
Определите условие выхода
Определите условие или ситуацию, в которой вы хотите завершить работу программы. Оно может быть основано на вводе пользователя, определенном событии, состоянии ошибки или любых других критериях, требующих остановки программы.
Используйте sys.exit() для завершения программы
Если условие завершения истинно, вызовите функцию sys.exit() , чтобы остановить выполнение программы. В качестве аргумента ей можно передать необязательный код состояния выхода, указывающий на причину завершения.
Опять же, код состояния 0 обычно используется для обозначения успешного завершения программы, в то время как ненулевые значения представляют различные типы ошибок или исключительных условий.
Вы также можете передать код состояния для предоставления дополнительной информации:
Очистка ресурсов (опционально)
Допустим, ваша программа использует ресурсы, которые должны быть надлежащим образом освобождены перед завершением. Примеры — закрытие файлов или освобождение сетевых соединений. В таком случае перед вызовом sys.exit() можно включить код очистки. Это гарантирует, что ресурсы будут обработаны должным образом, даже если программа завершится неожиданно.
Документируйте условия выхода
Важно документировать конкретные условия завершения в коде и оставлять комментарии, указывающие, почему программа завершается. Это поможет другим разработчикам понять цель и поведение вызовов exit() .
Заключение
Теперь вы знаете, как использовать функцию exit в Python для завершения выполнения программы. По желанию можно передать в эту функцию в качестве аргумента код состояния, предоставляя дополнительную информацию о причине завершения.
Соблюдая правила, приведенные в этой статье, вы сможете эффективно использовать exit() для остановки программы в случае необходимости.
Очень важно проявлять осторожность и применять эту функцию разумно. Она должна использоваться только в соответствующих обстоятельствах, когда вы хотите принудительно остановить выполнение вашего скрипта Python при определенных условиях или когда вам нужно завершить программу немедленно.
Python exit command (quit(), exit(), sys.exit())
Let us check out the exit commands in python like quit(), exit(), sys.exit() commands.
Python quit() function
In python, we have an in-built quit() function which is used to exit a python program. When it encounters the quit() function in the system, it terminates the execution of the program completely.
It should not be used in production code and this function should only be used in the interpreter.
Example:
After writing the above code (python quit() function), Ones you will print “ val ” then the output will appear as a “ 0 1 2 “. Here, if the value of “val” becomes “3” then the program is forced to quit, and it will print the quit message.
You can refer to the below screenshot python quit() function.
Python exit() function
We can also use the in-built exit() function in python to exit and come out of the program in python. It should be used in the interpreter only, it is like a synonym of quit() to make python more user-friendly
Example:
After writing the above code (python exit() function), Ones you will print “ val ” then the output will appear as a “ 0 1 2 “. Here, if the value of “val” becomes “3” then the program is forced to exit, and it will print the exit message too.
You can refer to the below screenshot python exit() function.
Python sys.exit() function
In python, sys.exit() is considered good to be used in production code unlike quit() and exit() as sys module is always available. It also contains the in-built function to exit the program and come out of the execution process. The sys.exit() also raises the SystemExit exception.
Example:
After writing the above code (python sys.exit() function), the output will appear as a “ Marks is less than 20 “. Here, if the marks are less than 20 then it will exit the program as an exception occurred and it will print SystemExit with the argument.
You can refer to the below screenshot python sys.exit() function.
Python os.exit() function
So first, we will import os module. Then, the os.exit() method is used to terminate the process with the specified status. We can use this method without flushing buffers or calling any cleanup handlers.
Example:
After writing the above code (python os.exit() function), the output will appear as a “ 0 1 2 “. Here, it will exit the program, if the value of ‘i’ equal to 3 then it will print the exit message.
You can refer to the below screenshot python os.exit() function.
Python raise SystemExit
The SystemExit is an exception which is raised, when the program is running needs to be stop.
Example:
After writing the above code (python raise SystemExit), the output will appear as “ 0 1 2 3 4 “. Here, we will use this exception to raise an error. If the value of ‘i’ equal to 5 then, it will exit the program and print the exit message.
You can refer to the below screenshot python raise SystemExit.
Program to stop code execution in python
To stop code execution in python first, we have to import the sys object, and then we can call the exit() function to stop the program from running. It is the most reliable way for stopping code execution. We can also pass the string to the Python exit() method.
Example:
After writing the above code (program to stop code execution in python), the output will appear as a “ list length is less than 5 “. If you want to prevent it from running, if a certain condition is not met then you can stop the execution. Here, the length of “my_list” is less than 5 so it stops the execution.
You can refer to the below screenshot program to stop code execution in python.
Difference between exit() and sys.exit() in python
- exit() – If we use exit() in a code and run it in the shell, it shows a message asking whether I want to kill the program or not. The exit() is considered bad to use in production code because it relies on site module.
- sys.exit() – But sys.exit() is better in this case because it closes the program and doesn’t ask. It is considered good to use in production code because the sys module will always be there.
In this Python tutorial, we learned about the python exit command with example and also we have seen how to use it like:
- Python quit() function
- Python exit() function
- Python sys.exit() function
- Python os.exit() function
- Python raise SystemExit
- Program to stop code execution in python
- Difference between exit() and sys.exit() in python
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.