Команда закончить код 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.

for val in range(0,5): if val == 3: print(quit) quit() print(val)

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 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

for val in range(0,5): if val == 3: print(exit) exit() print(val)

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 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.

import sys marks = 12 if marks < 20: sys.exit("Marks is less than 20") else: print("Marks is not less than 20")

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.

Читайте также:  Интерфейс командной строки python

You can refer to the below screenshot python sys.exit() function.

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.

import os for i in range(5): if i == 3: print(exit) os._exit(0) print(i)

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 os.exit() function

Python raise SystemExit

The SystemExit is an exception which is raised, when the program is running needs to be stop.

for i in range(8): if i == 5: print(exit) raise SystemExit print(i)

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.

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.

import sys my_list = [] if len(my_list) < 5: sys.exit('list length is less than 5')

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.

python exit command

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.
Читайте также:  Python keras save and load model

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.

Источник

Как использовать функцию exit в скриптах Python

Функция exit в Python позволяет в любой момент остановить выполнение скрипта или программы. Это может понадобиться для обработки ошибок, тестирования и отладки, остановки программы при соблюдении каких-то условий.

Необязательный аргумент status представляет собой статус выхода. Это целочисленное значение, которое указывает на причину завершения программы. Принято считать, что статус 0 означает успешное выполнение, а любой ненулевой статус указывает на ошибку или ненормальное завершение.

Если аргумент status не указан, используется значение по умолчанию 0.

Вот пример использования функции exit в Python:

print("Before exit") exit(1) print("After exit") # This line will not be executed

В этом примере программа выводит строку «Before exit». Но когда exit() вызывается с аргументом 1, программа немедленно завершается, не выполняя оставшийся код. Поэтому строка «After exit» не выводится.

От редакции Pythonist: также предлагаем почитать статьи «Как запустить скрипт Python» и «Создание Python-скрипта, выполняемого в Unix».

Как использовать функцию exit() в Python

Давайте напишем скрипт на Python и используем в нем функцию exit.

import sys def main(): try: print("Welcome to the program!") # Check for termination condition user_input = input("Do you want to exit the program? (y/n): ") if user_input.lower() == "y": exit_program() # Continue with other operations except Exception as e: print(f"An error occurred: ") exit_program() def exit_program(): print("Exiting the program. ") sys.exit(0) if __name__ == "__main__": main()

Пояснение кода

  1. Скрипт начинается с импорта модуля sys, который предоставляет доступ к функции exit() .
  2. Функция main() служит точкой входа в программу. Внутри этой функции можно добавлять свой код.
  3. Внутри функции main() можно выполнять различные операции. В данном примере мы просто выводим приветственное сообщение и спрашиваем пользователя, хочет ли он выйти.
  4. После получения пользовательского ввода мы проверяем, хочет ли пользователь выйти. Для этого сравниваем его ввод с «y» (без учета регистра). Если условие истинно, вызываем функцию exit_program() для завершения работы скрипта.
  5. Функция exit_program() выводит сообщение о том, что программа завершается, а затем вызывает sys.exit(0) для завершения программы. Аргумент 0, переданный в sys.exit() , означает успешное завершение программы. При необходимости вы можете выбрать другой код завершения.
  6. Наконец, при помощи переменной __name__ проверяем, выполняется ли скрипт как главный модуль. Если это так, вызываем функцию main() для запуска программы.
Читайте также:  Блок посередине экрана css

Best practices использования функции exit в Python

Импортируйте модуль sys

Чтобы использовать функцию exit(), необходимо импортировать модуль sys в начале скрипта. Включите в свой код следующую строку:

Определите условие выхода

Определите условие или ситуацию, в которой вы хотите завершить работу программы. Оно может быть основано на вводе пользователя, определенном событии, состоянии ошибки или любых других критериях, требующих остановки программы.

Используйте sys.exit() для завершения программы

Если условие завершения истинно, вызовите функцию sys.exit() , чтобы остановить выполнение программы. В качестве аргумента ей можно передать необязательный код состояния выхода, указывающий на причину завершения.

Опять же, код состояния 0 обычно используется для обозначения успешного завершения программы, в то время как ненулевые значения представляют различные типы ошибок или исключительных условий.

if condition_met: sys.exit() # Terminate the program with status code 0

Вы также можете передать код состояния для предоставления дополнительной информации:

if error_occurred: sys.exit(1) # Terminate the program with status code 1 indicating an error

Очистка ресурсов (опционально)

Допустим, ваша программа использует ресурсы, которые должны быть надлежащим образом освобождены перед завершением. Примеры — закрытие файлов или освобождение сетевых соединений. В таком случае перед вызовом sys.exit() можно включить код очистки. Это гарантирует, что ресурсы будут обработаны должным образом, даже если программа завершится неожиданно.

Документируйте условия выхода

Важно документировать конкретные условия завершения в коде и оставлять комментарии, указывающие, почему программа завершается. Это поможет другим разработчикам понять цель и поведение вызовов exit() .

Заключение

Теперь вы знаете, как использовать функцию exit в Python для завершения выполнения программы. По желанию можно передать в эту функцию в качестве аргумента код состояния, предоставляя дополнительную информацию о причине завершения.

Соблюдая правила, приведенные в этой статье, вы сможете эффективно использовать exit() для остановки программы в случае необходимости.

Очень важно проявлять осторожность и применять эту функцию разумно. Она должна использоваться только в соответствующих обстоятельствах, когда вы хотите принудительно остановить выполнение вашего скрипта Python при определенных условиях или когда вам нужно завершить программу немедленно.

Источник

Оцените статью