- How to Exit a Python script?
- Exiting a Python application
- Example: Exit Using Python exit() Method
- Python3
- Detecting Script exit
- How Do You End Scripts in Python?
- 5 Ways to End Python Scripts
- 1. All the Lines Are Executed
- 2. Uncaught Exception
- 3. sys.exit()
- 4. exit() and quit()
- 5. External Interruption
- Как остановить работу программы Python?
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
this is the first statement
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.
In the following code, we would be defining (and registering) a function that would be called upon the termination of the program. First, the atexit module is imported. Then exit_handler() function is defined. This function contains a print statement. Later, this function is registered by passing the function object to the atexit.register() function. In the end, there is a call to print function for displaying GFG! in the output. In the output, the first line is the output of the last print statement in the code. The second line contains the output of exit_handler function that is called upon the code execution (as a cleanup function).
Not all kinds of exits are handled by the atexit module.
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!
Как остановить работу программы Python?
Есть программа, которая должна работать до какого-то момента, если не остановить, то бесконечно. Хочу как-нибудь "красиво" останавливать программу, но не знаю как.
Jairman, какой вопрос - такой и ответ.
В идеале - скрипт не нужно завершать, у него должно быть логическое завершение. Если есть необходимость останавливать скрипт вручную, то нужно смотреть на сам скрипт, потому что вариантов, как остановить выполнение - куча. Как вариант - обрабатывать исключение KeyboardInterrupt и по нажатию ctrl + c внутри самого скрипта останавливать процессы.
Ivan Yakushenko, вы слишком усложняете) для того что бы иметь статус - Куратор тега Python
вы все правильно говорите, что программа должна логический конец иметь, но судя по вопросу требуется именно тупое прерывание программы в тот момент где захочет ее создатель) программным методом, без пальцев)
artem_sib, ничего я не усложняю. Для реализации точки выхода из приложения, которая гарантирует завершение всех процессов, нужно смотреть на реализацию самого приложения. А под